Tuesday 16 May 2017

Need a way or a tool to await a code block in node

The ES2017 async/await feature is great. It reduces the pain of writing recursive callbacks. However, I sometime see nodejs runtime warning like unhandled promise rejection. The reason is that I have forgotten to put await every where inside an async code block

function action1Async() {
  return new Promise((resolve, reject) => {
    resolve('good name async function')
  })
}
async function action2() {
  return new Promise((resolve, reject) => {
    reject('bad name async function')
  })
}

async function main() {
  const r1 = await action1Async()
  const r2 = action2() // The name is bad, I dont realize it is an async function. Actually throw an exception
  return r1 + r2
}

As you can see from the code example, unless I put await at every single function call, it will be very easy to let code go wrong. I believe there is a reason that ES draft community to invent await for control the behavior inside an async block.

There is no problem for me to write correct code. But I think it will be too comprehensive to write so many await inside a code block that I intent to run in synchronous. Is it possible to automatically resolve all promises inside a code block, just like a coroutine? With some static tool or magical JS library?

Thanks in advance



via stanleyxu2005

No comments:

Post a Comment