I've seen a few articles explaining the concept of promise and async/await, here is an example.
But I still can't figure out how the following code works and why the output is that.
I will appreciate it if someone can solve my confusion.
code
const promiseFn = (n) =>
new Promise((res, rej) => {
res(n);
});
promiseFn(1)
.then((data) => {
console.log(data);
return promiseFn(2);
})
.then((data) => {
console.log(data);
});
const data3 = await promiseFn(3);
console.log(data3);
const data4 = await promiseFn(4);
console.log(data4);
The output is:
1 3 4 2
But what I thought the output should be
1 3 2 4
And I thought the code of async/await might be converted to the following
const promiseFn = (n) =>
new Promise((res, rej) => {
res(n);
});
promiseFn(1)
.then((data) => {
console.log(data);
return promiseFn(2);
})
.then((data) => {
console.log(data);
});
Promise.resolve(promiseFn(3))
.then((data) => {
console.log(data);
return Promise.resolve(promiseFn(4));
})
.then((data) => {
console.log(data);
});
But the output is below which is not as same as the async/await version.
1 3 2 4
So I think I misunderstood the difference between Promise
and async/await
.
Thank so much you for helping me figure it out.
Based on the code of promise
version above, I tried to wrap the 2nd promise to the 1st one instead of returning the function as below,
the output seems to be different which made me even more confused.
const promiseFn = (msg) =>
new Promise((res, rej) => {
res(msg);
});
promiseFn(1)
.then((data) => {
console.log(data);
return promiseFn(2);
})
.then((data) => {
console.log(data);
});
Promise.resolve(promiseFn(3)).then((data) => {
console.log(data);
Promise.resolve(promiseFn(4)).then((data) => {
console.log(data);
});
});
output :
1 3 4 2