Node exits before async function completes

巧了我就是萌 提交于 2019-12-10 02:13:41

问题


I have a function that returns a promise, and I am trying to await on it from within an async function. The problem is that the program completes immediately, instead of awaiting the promise.

async-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" );

Build and run:

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

Result:

awaiting
passed by the test

Resolving immediately instead of waiting one second has no effect:

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

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

    return deferred;
}

Interestingly, "resolving" is never printed, even though it is now synchronous:

awaiting
passed by the test

I would suspect a compiler problem, but I checked Babel's output and sure enough, it did compile the synchronous version.

I thought I could just await on a promise from within an async function. Is there something I am missing here?


回答1:


You are not using Promise right (assuming it's standard compliant). It doesn't have resolve method. You should pass a function instead:

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


来源:https://stackoverflow.com/questions/31124968/node-exits-before-async-function-completes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!