முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 7 · பாடம் 2 இன் 4பாடத்திட்டத்தில் 26/32~12 min
தொகுதி பாடங்கள் (2/4)

ஒத்திசைவு / காத்திரு

async/await is a clearer syntax for working with Promises: the code reads like synchronous code, but behind the scenes it uses exactly the same Promises as the previous lesson.

async function

A function declared with async always returns a Promise.

JS
async function forty() {
  return 40;
}

forty(); // Promise { 40 }
forty().then((v) => console.log(v)); // 40

Even if you return a "normal" value, the function wraps it in a resolved Promise.

await

Inside an async function you can put await before a Promise: execution is paused until the Promise settles, then continues with the resolved value.

JS
async function sum() {
  const a = await Promise.resolve(10);
  const b = await Promise.resolve(20);
  return a + b; // 30
}

Equivalent in .then style (more verbose):

JS
function sum() {
  return Promise.resolve(10).then((a) => Promise.resolve(20).then((b) => a + b));
}

await propagates errors

If the Promise is rejected, await rethrows the error. You can catch it with a normal try/catch:

JS
async function read() {
  try {
    const x = await Promise.reject(new Error('no'));
    return x;
  } catch (err) {
    return 'error: ' + err.message;
  }
}

read(); // Promise { 'error: no' }

Arrow async

JS
const double = async (n) => n * 2;
double(5); // Promise { 10 }

Try it

உடற்பயிற்சி#js.m7.l2.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Define an `async function addOne(p)` that receives a Promise of a number and returns (as a Promise) the number + 1. Use await.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

const n = await p; return n + 1;

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#js.m7.l2.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Define `sumTwo(pa, pb)` async: receives two Promises of numbers, returns their sum. Use two sequential awaits.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

await each one, then return a + b.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்