Node exits before async function completes

2020-08-17 18:07发布

问题:

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 );
   }); 
 }