nodejs, using 'await' within finis handling

220
March 08, 2018, at 3:55 PM

In my finis callback, I have:

finis((code, signal, error) => {
  await myprocess.stop()
  console.log(`finis(${code}, ${signal}, ${error})`)
})

However, I'm getting the error:

Can not use keyword 'await' outside an async function

So how to do await within finis' callback?

PS. finis()'s callback function will be run just before the node process exits, and I want to gracefully shutdown myprocess by myprocess.stop() before program exist.

Answer 1

Try the following.

finis(async (code, signal, error) => {
  await myprocess.stop()
  console.log(`finis(${code}, ${signal}, ${error})`)
})
Answer 2

The syntax error can be fixed by declaring your callback to be async.

But, it appears that you have bigger issues than that because you want the caller of your callback (the function finis) to wait for your asynchronous operation to complete before it does the rest of its work. await inside your callback by itself will not do that.

Here are a few notes about what await does:

  1. await only does anything useful if you await a promise. It has no magic powers to await some mythical asynchronous operation. It only awaits a promise. So, in your particular code, myprocess.stop() must return a promise that it resolved when the underlying asynchronous operation in myprocess.stop() completes for the await in await myprocess.stop() to do anything useful.

  2. await only blocks execution within the local async function. The containing function still returns as soon as you hit the first await. So, it won't block the caller at all.

  3. An async function (that you can use await in) returns a promise so the only way the caller of that function (the caller of your callback in your case which is finis() would actually wait for your async operation to complete is if it was expecting the callback to return a promise and if it used either .then() or await on that callback itself.

If you control the code for the finis() function, then we could probably help you modify it to do what you want (to look for a returned promise before it shuts things down), but if you don't control that function, then you're probably out of luck.

Rent Charter Buses Company
READ ALSO
mongo aggregation adding dates and sums

mongo aggregation adding dates and sums

I feel like this could be really complexI know this is possible in JS by taking each record, determine the difference in months, then increase each model

204
How to access routes folder in sailsjs

How to access routes folder in sailsjs

My routejs file is becoming larger

193
src\debug-agent.cc:149: Assertion `(err) == (0)' failed

src\debug-agent.cc:149: Assertion `(err) == (0)' failed

I get the above error trying to run node-debugI'm using node-inspector v1

235