On https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function they say that writing
async function foo() {
return 1
}
is the same as writing
function foo() {
return Promise.resolve(1)
}
So that means that if we want to 'transform' a promise into an async function, we have to replace resolve(promise_result)
with return promise_result
.
But when I try to use setTimeout
with async
it doesn't work:
const test1 = async () => {
setTimeout(
() => {
return 5;
},
2000,
)
}
const test2 = () => new Promise(
(resolve, reject) => {
setTimeout(
() => resolve(25),
1000
)
}
)
const execute = async () => {
const result = await test1();
console.log(result); // undefined
}
execute();
If I use await
on test2
it works but it doesn't work on test1
. Why is that ? Is async/await
only meant to deal with pending promises without using .then
or can I use async
with return result
instead of using Promise
with resolve
?
Its undefined because test1
does not return anything back. take a closer look you return it in the anonymous function back
const test1 = async () => { // <--- this function returns nothing back. Nothing means "undefined"
setTimeout(
() => { // <---- you return it here back in your anonymous function witch makes no sense
return 5;
},
2000,
)
}
That's a fun one. The problem here is that
const test1 = async () => {
setTimeout(
() => {
return 5;
},
2000,
)
}
test1 is an async function, BUT setTimeout
is not.
setTimeout
will just schedule whatever you pass it and return its timeoutID immediately. In such a case, you'd really need to handle the Promise code manually .
You forgot to await setTimeout
in test1
. What happens is that you return a promise of a promise. The first promise is awaited but the second one (that is wrapped inside the first is not), whereas in test2
you return directly a promise.
It's more clear in typescript, where the type of test1
should be Promise<Promise<number>>
and the type of test2
should be Promise<number>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.