nodejs,在finis处理中使用"await" [英] nodejs, using 'await' within finis handling

查看:60
本文介绍了nodejs,在finis处理中使用"await"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 finis 回调中,我有:

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

但是,我得到了错误:

Can not use keyword 'await' outside an async function

那么如何在 finis '回调中等待呢?

So how to do await within finis' callback?

PS. finis()的回调函数将在节点进程退出之前运行,我想通过 myprocess.stop()正常关闭 myprocess > 之前程序存在.

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.

推荐答案

可以通过将回调声明为 async 来修复语法错误.

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

但是,看来您要解决的问题要大得多,因为您希望回调的调用方(函数 finis )在完成其余工作之前等待异步操作完成.回调内部的 await 本身不会这样做.

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.

以下是有关 await 所做的一些注意事项:

Here are a few notes about what await does:

  1. await 仅在您 await 一个承诺时才有用.它没有魔力来等待一些神话般的异步操作.它只是在等待一个诺言.因此,在您的特定代码中, myprocess.stop()必须返回一个承诺,该承诺将在 myprocess.stop()中的基础异步操作完成对 await myprocess.stop()中的await 中执行任何有用的操作.

  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.

await 仅阻止在本地 async 函数中执行.只要您按下第一个 await ,包含函数仍会返回.因此,它根本不会阻止呼叫者.

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.

一个 async 函数(可以在其中使用 await )可以返回一个Promise,因此,该函数的调用者(回调函数的调用者)是唯一的方式.您的案例 finis()实际上会等待您的异步操作完成,如果它希望回调返回一个诺言并且是否使用了 .then()或在回调本身上 await .

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.

如果您控制 finis()函数的代码,那么我们可能可以帮助您修改它以执行所需的操作(在关闭之前查找返回的诺言),但是如果您不控制该功能,则可能很不走运.

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.

这篇关于nodejs,在finis处理中使用"await"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆