After seeing some code in which an await
was return
ed, I was trying to understand if it were better to create an async function to and return the await or just return a promise. To me they should really both just be returning promises.
const P = (payload, ms) => {
return new Promise(resolve => {
setTimeout(() => {
resolve('promise resolved! payload ' + payload)
}, ms)
})
}
const verify1 = async () => {
return await P('>>> 1', 0)
}
const verify2 = () => {
return P('>>> 2', 0)
}
verify1().then(message => console.log(message))
verify2().then(message => console.log(message))
However running this with various values produced a result I wasn't really expecting
return await P('>>> 1', 10)
return P('>>> 2', 0)
^^^ "2" returns first - makes sense
return await P('>>> 1', 0)
return P('>>> 2', 10)
^^^ "1" returns first - makes sense
return await P('>>> 1', 0)
return P('>>> 2', 0)
^^^ "2" returns first
Why does 2 return first when both are given a timeout of 0
? Is this just a result of wrapping within an additional promise? Is there any reason ever to return await
?