【问题标题】:Node exits before async function completes节点在异步函数完成之前退出
【发布时间】:2015-06-29 20:28:46
【问题描述】:

我有一个返回 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 的输出,果然,它确实编译了同步版本。

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 2016-07-16
      • 1970-01-01
      相关资源
      最近更新 更多