异步等待和承诺-如何改进语法

时间:2019-02-02 07:30:33

标签: javascript async-await es6-promise

一个人如何创建语法糖来隐藏.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当前的工作方式)确定。

3 个答案:

答案 0 :(得分:2)

可以使用await前述myFridge.openDoor()调用包裹在括号以形成表达然后链.eatCake()调用从返回的对象的方法.openDoor()

(async() => {
  (await myFridge.openDoor()).eatCake()
})()

答案 1 :(得分:1)

有一种称为100/2 = 50的语法 与try()catch()

结合使用

示例:

async await

而不是使用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(),在此之下,您可以继续使用已解析的值编写更多代码 而不是将更多函数与回调链接在一起

用一只脚很难解释和理解,所以这里有些resource for async await

答案 2 :(得分:0)

这是提供语法糖的解决方案,可用于隐藏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()