node.js - Node 在异步函数完成之前退出

标签 node.js async-await babeljs ecmascript-2016

我有一个返回 promise 的函数,我试图在异步函数中等待它。问题是程序立即完成,而不是等待 promise 。

异步测试.js:

function doItSlow() {
    const deferred = new Promise();

    setTimeout( () => {
        console.log( "resolving" );
        deferred.resolve();
    }, 1000 );

    return deferred;
}

async function waitForIt( done ) {

    console.log( "awaiting" );
    await doItSlow();
    console.log( "awaited" );
    done();
}

waitForIt(() => {
    console.log( "completed test" );
});

console.log( "passed by the test" );

构建并运行:

babel --stage 0 --optional runtime async-test.js > at.js && node at.js`

结果:

awaiting
passed by the test

立即解决而不是等待一秒钟没有效果:

function doItSlow() {
    const deferred = new Promise();

    console.log( "resolving" );
    deferred.resolve();

    return deferred;
}

有趣的是,“resolving”永远不会被打印出来,即使它现在是同步的:

awaiting
passed by the test

我怀疑是编译器问题,但我检查了 Babel 的输出,果然,它编译了同步版本。

我以为我可以等待异步函数中的 promise 。我在这里有什么遗漏吗?

最佳答案

您没有正确使用 Promise(假设它符合标准)。它没有 resolve 方法。你应该传递一个函数:

function doItSlow() {
  return new Promise(resolve => {
    setTimeout( () => {
      console.log( "resolving" );
      resolve();
    }, 1000 );
   }); 
 }

关于node.js - Node 在异步函数完成之前退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31124968/

相关文章:

node.js - 在 Godaddy 上托管 React 应用程序

javascript - Puppeteer 中的异步/等待等待页面加载

c# - 将泛型方法转换为异步导致泛型参数出现问题

vue.js - 使用目标 wc 构建选项时,vue-cli 不会将代码转换为 es5 或 commonjs

javascript - Meteor 应用程序链接到外部页面/应用程序

facebook - 如何使用 sails.js 访问外部 api?

c# - 如何等待 Func<Task<string>>?

typescript - Vue cli 3 - 找不到模块 '@vue/cli-plugin-babel'

javascript - 引用错误 : You are trying to `import` a file after the Jest environment has been torn down: at loadCjsDefault

javascript - Webpack 开发服务器抛出错误 - 拒绝执行脚本,因为它的 MIME 类型 ('text/html' )不可执行