I'm learning to use async/await and this is quite confused to me. As I know, async
functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
async function foo() {
setTimeout(() => {
throw new Error('error');
}, 5000);
}
async function test() {
try {
await foo();
} catch (err) {
console.log(err);
}
console.log('not reached');
}
test();
- Expected output: log the error after 5 secs, then log "not reach".
- What actually happened: "not reach" gets logged right after I start the script, then the error gets logged after 5 seconds.
- Attempts: the following code does exactly what I want, but I don't know what's the difference between those code.
- Environment: nodejs 16.14.2
function foo() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('foo'));
}, 5000);
});
}
async function test() {
try {
await foo();
} catch (err) {
console.log(err);
}
console.log('not reached');
}
test();
Thanks a lot!
CodePudding user response:
foo needs to actually resolve
Your example doesn't work because foo
doesn't actually care about the timeout. It just starts the timeout then returns immediately. What you need to do is make foo
resolve when the timeout fires, which actually requires you to construct a Promise explicitly.
async function foo() {
return new Promise(resolve => {
setTimeout(resolve, 5000)
})
}
Since you return a Promise, you could technically not declare foo
as async, but it doesn't matter, and (I think) it's still helpful for other developers to see that the function returns a Promise without having to look through the implementation.
CodePudding user response:
In your second example, foo returns a promise, setTimeout needs to produce a promise for it to work in your example.
For example
async function foo() {
// promise returned
return new Promise(resolve => {
setTimeout(() => { resolve() } , 5000)
})
}