0%

javascript-async-await

await works with promise chain

In JavaScript, await can works with promise chain, it will get the resolved value of the last promise in the chain. For example:

1
2
3
4
5
6
7
8
9
10
11
getData = () =>
Promise.resolve(1)
.then(() => 2)
.then(() => 3);

async function test() {
const res = await getData(); // output: 3
console.log(res);
}

test();

In above code, getData() returns a promise chain, the resolved value of the last promise in the chain is 3, so the output of the code is 3.

You can even append more promise chain when calling getData()

1
2
3
4
5
6
async function test() {
const res = await getData()
.then(() => 4)
.then(() => 5);
console.log(res); // output: 5
}