节点在异步功能完成之前退出

Dan*_*oss 10 node.js async-await babeljs ecmascript-7

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

异步test.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" );
Run Code Online (Sandbox Code Playgroud)

构建并运行:

babel --stage 0 --optional runtime async-test.js > at.js && node at.js`
Run Code Online (Sandbox Code Playgroud)

结果:

awaiting
passed by the test
Run Code Online (Sandbox Code Playgroud)

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

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

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

    return deferred;
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,"解析"从未打印过,即使它现在是同步的:

awaiting
passed by the test
Run Code Online (Sandbox Code Playgroud)

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

我以为我可以等待异步函数中的一个承诺.这里有什么我想念的吗?

vku*_*kin 8

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

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