1 回答
TA贡献1799条经验 获得超9个赞
警告await只能在async函数内部使用,您想要的那种 API 是可能的,只是稍微复杂一些。
大量的库,例如knex,jQuery和nightmare.js实现链接以组成异步操作。但是可链接的方法不是异步的。相反,异步操作仅在操作结束时(当您想要结果时)执行,但方法本身是同步的。在的情况下knex,例如,异步操作仅执行时.then()被调用。
这是您可以做到的一种方法:
function Calc () {
this.operations = [];
this.value = 0;
}
Calc.prototype = {
add: function (x) {
// schedule a function that performs async addition:
this.operations.push(() => {
return new Promise(ok => {
ok(this.value + x);
});
});
return this;
},
subtract: function (x) {
// schedule a function that performs async subtraction:
this.operations.push(() => {
return new Promise(ok => {
ok(this.value - x);
});
});
return this;
},
// THIS IS WHERE WE DO OUR MAGIC
then: async function (callback) {
// This is finally where we can execute all our
// scheduled async operations:
this.value = 0;
for (let i=0; i<this.operations.length; i++) {
this.value = await operations[i]();
}
return callback(this.value); // since the await keyword will call our
// then method it is the responsibility of
// this method to return the value.
}
}
现在你可以像这样使用它:
async function main () {
let x = await new Calc().add(2).subtract(1);
console.log(x);
}
main();
请注意,上面的代码在功能上等效于:
new Calc().add(2).subtract(1).then(x => console.log(x));
添加回答
举报