【发布时间】:2019-02-02 07:30:32
【问题描述】:
如何创建语法糖来隐藏 .then 的一些复杂性?
给定下面的代码:
const Fridge = {
async openDoor() {
const myCake = new Promise(resolve => {setTimeout(()=> {
console.log('door opened')
resolve (Object.create(Cake))
}, 2000)});
await myCake
return myCake
}
}
const Cake= {
eatCake(){ console.log ( 'yummy now I can eat my cake' ) }
}
const myFridge = Object.create(Fridge)
通常通过详细访问:
myFridge.openDoor().then(myCake=>{
myCake.eatCake()
... other code here .....
}) // complicated
是否可以创建一些糖来代替:
myFridge.openDoor().eatCake() //simple to understand .then implied
或者更进一步,而不是:
myObject.myPromise.then(res=>{
let x = res
... do stuff with x
});
相当
let x = myObject.myPromise.res
... so stuff with x
从异步函数返回的任何内容都应该用于后续调用。并且假定所有后续代码都在 .then 中。 .then 的关闭由封闭函数的结尾决定(类似于 await 当前的工作方式)。
【问题讨论】:
-
现在我想要一个蛋糕!非常感谢你!我在这里节食... :(
标签: javascript async-await es6-promise