0

After seeing some code in which an await was returned, 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?

1252748
  • 14,597
  • 32
  • 109
  • 229
  • "*Is this just a result of wrapping within an additional promise?*" - yes, exactly that. – Bergi Oct 01 '18 at 19:20
  • @Bergi I was hoping to address his question regarding _why_ you might `return await`. Mind reopening? – Matthew Herbst Oct 01 '18 at 19:21
  • @Bergi Indeed, I would be interested in that as well, as the question you linked seems only to address performance. – 1252748 Oct 01 '18 at 19:22
  • 2
    The first duplicate target might mention performance in the title, but the answer explains: don't ever use it, it's bad style, except inside a `try` block. – Bergi Oct 01 '18 at 19:25
  • If you don't have control over the name of the function you're returning, i.e., `get`, it might be more clear that `get` is a promise if you `return await get()` rather than `return get()`, but it would probably be preferred that you rename it so you can `return getAsync()` if possible. – Cody G Oct 01 '18 at 20:04

0 Answers0