简体   繁体   中英

Async Await and Promises - how to improve the syntax

How could one create syntactical sugar to hide some of the complexity that is .then?

Given the code below:

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)

Typically accessed via the verbatious:

myFridge.openDoor().then(myCake=>{
  myCake.eatCake()
  ... other code here .....
}) // complicated

Can some sugar be created to instead:

myFridge.openDoor().eatCake()  //simple to understand .then implied

or further, instead of:

myObject.myPromise.then(res=>{
   let x = res
   ... do stuff with x
});

rather

let x = myObject.myPromise.res
... so stuff with x

Whatever is returned from the async function should be used for the subsequent call. And all subsequent code is assumed to be in the .then. Closure of the .then is determined by the end of the enclosing function (similar to how the await currently works).

You can use await preceding myFridge.openDoor() call wrapped in parenthesis to form an expression then chain .eatCake() to call the method of the object returned from .openDoor()

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

there is a syntax called try()catch() in Combine with async await

example:

async function someAsyncFunction () {
   try {
      const asyncValue = await asyncCall() //Promise
      console.log(asyncValue) // this will log only when asyncCall resolved
    }catch(error) {
     throw error
   }
  }

instead of using Promise and chain a then() with a callback to it.

you do await asyncCall() and under that you can keep writing more code with the resolved value instead of chaining more functions with callbacks

Its hard to explain and understand on 1 foot so here is some resource for async await

Here is a solution that provides syntactical sugar that can be used to hide the complexities of await and .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))
  }
}

Can be accessed via:

Fridge.openDoor().eatCake('Yummy').getFat()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM