节点在异步功能完成之前退出 [英] Node exits before async function completes

查看:103
本文介绍了节点在异步功能完成之前退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

构建并运行:

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

结果:

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

有趣的是,即使现在是同步的,"resolving"也不会被打印:

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

awaiting
passed by the test

我会怀疑编译器有问题,但是我检查了Babel的输出,并且肯定地,它确实编译了同步版本.

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?

推荐答案

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

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

这篇关于节点在异步功能完成之前退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆