Reputation: 138
How are these 2 not equivalent?
This doesn't work.
const message = async () => {
setTimeout(() => {
console.log("delayed")
return true
}, 1000)
}
but this does?
const message = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("delayed")
resolve(true)
}, 1000)
})
}
Does this mean you can only "return" in an async function if it is directly in the scope of the function(not in another function)?
Is the promise returned by an async function different than a regular promise? How is it initialized exactly?
Upvotes: 0
Views: 31
Reputation: 943635
The message
function in your first example has no return
statement to pass a value for its resolution.
The Promise in your second example passes a value to resolve()
explicitly.
Does this mean you can only "return" in an async function if it is directly in the scope of the function(not in another function)?
Yes. The return value of a function is determined by a return
statement in that function. Putting a return
statement in some other function will set the return value for that function.
Upvotes: 5