我正在尝试在类中调用嵌套的异步函数,如果 2017 年的新异步/等待功能甚至可以实现的话。
下面是我使用 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();
我期待的是打印这段代码 一 二 三
但是,它只打印 一个
似乎没有对 this.two() 和 this.three 进行后续调用。几天来一直在尝试调试这个问题。
最佳答案
你的 promise 永远不会兑现:
return new Promise(function (resolve) {
});
那里应该有一些对 resolve
的调用。但是,如果您只是想让 async
函数返回一个 promise,那么根本就不要创建一个 promise:async
函数总是返回一个 promise,而这已经发生了当遇到第一个 await
时。 promise 的值 是您使用return
返回的任何内容。因此,不要返回 promise ,但不返回任何内容(即 undefined
)或您希望 promise 解决的其他一些值。
只是为了说明,在支持 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();
关于JavaScript ES2017 : Nested async await in a class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43950797/