[英]How can I improve the speed of this code with proper async/await/promises
[英]Async Await and Promises - how to improve the syntax
一个人如何创建语法糖来隐藏.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当前的工作方式)确定。
您可以在括号中的myFridge.openDoor()
调用之前使用await
来形成表达式,然后链接.eatCake()
来调用从.openDoor()
返回的对象的方法
(async() => {
(await myFridge.openDoor()).eatCake()
})()
与async await
结合使用时有一种名为try()catch()
的语法
例:
async function someAsyncFunction () {
try {
const asyncValue = await asyncCall() //Promise
console.log(asyncValue) // this will log only when asyncCall resolved
}catch(error) {
throw error
}
}
而不是使用Promise
并将一个带有回调的then()
起来。
您确实要await asyncCall()
,在此之下,您可以继续使用已解析的值编写更多代码,而不用通过回调链接更多函数
很难解释和理解,所以这里有一些异步等待的资源
这是一个提供语法糖的解决方案,可用于隐藏await和.then的复杂性:
const promiseNodeH = {
get(target, prop) {
if (prop in target || typeof prop !== 'string') return target[prop]
return function() {
const x = arguments
const p3 = new Promise(resolve => {
target.then(value => {
resolve(value[prop](...x))
})
})
return new Proxy(p3, Object.create(promiseNodeH))
}
}
}
const Cake = {
eatCake(msg) {
console.log(`starting to eat cake: ${msg}!`)
const self = this
return new Promise(resolve => {
setTimeout(function() {
console.log('cake eaten')
resolve(self)
}, 5000)
})
},
getFat() {
console.log('burp')
}
}
const Fridge = {
openDoor() {
console.log('start to open door')
const p1 = new Promise(resolve => {
setTimeout(function() {
console.log('door is open, here is your cake')
resolve(Object.create(Cake))
}, 5000)
})
return new Proxy(p1, Object.create(promiseNodeH))
}
}
可以通过以下方式访问:
Fridge.openDoor().eatCake('Yummy').getFat()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.