Javascript ES2017:在类中嵌套异步等待

aus*_*123 2 javascript asynchronous node.js

我试图在类中调用嵌套的异步函数,如果在2017年使用新的async/await功能甚至可以实现.

下面是一些示例代码,我正在运行NodeJS v7.7.2:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Counter {
    async run() {
        await this.one();
        await this.two();
        await this.three();
        return new Promise(function (resolve) {
        });
    }
    async one() {
        console.log('one');
        return new Promise(function (resolve) {
        });
    }
    async two() {
        console.log('two');
        return new Promise(function (resolve) {
        });
    }
    async three() {
        console.log('three');
        return new Promise(function (resolve) {
        });
    }
}
exports.Counter = Counter;
let counter = new Counter();
counter.run();
Run Code Online (Sandbox Code Playgroud)

我期待发生的是这个代码打印一两三

但是,它只打印一个

似乎没有对this.two()和this.three的后续调用.一直试图调试这个问题几天.

tri*_*cot 7

你的承诺永远不会解决:

    return new Promise(function (resolve) {
    });
Run Code Online (Sandbox Code Playgroud)

那里应该有一些电话resolve.但是如果你只是试图让async函数返回一个promise,那么就不要创建一个promise:async函数总是返回一个promise,而这在await遇到第一个时就已经发生了.承诺的价值是你返回的任何东西return.因此,不要返回一个承诺,但是没有任何(即undefined)或者您希望承诺解决的其他值.

只是为了说明,在支持的浏览器async(例如Firefox 52+)中,以下代码段将输出一个,两个,三个:

class Counter {
    async run() {
        await this.one();
        await this.two();
        await this.three();
    }
    async one() {
        console.log('one');
    }
    async two() {
        console.log('two');
    }
    async three() {
        console.log('three');
    }
}
let counter = new Counter();
counter.run();
Run Code Online (Sandbox Code Playgroud)

  • 你甚至不需要`Promise.resolve`,只需要`return`.如果没有结果值,或者根本不"返回"任何东西. (3认同)