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));
添加回答
舉報