preface

ES6 Promise solves the common callback hell problem in Javascript code, and with async/await asynchronous logic can be written synchronously, greatly improving development efficiency.

However, there are still many libraries that do not implement promise-based interfaces, including the API of wechat mini program.

In order to write consistent code without compromising with the bad guys, it’s important to understand what promises are.

This article assumes that the reader has some JavaScript background and an understanding of the basic uses of Promises.

Callback interface

The asynchronous callback interface refers to passing functions to handle asynchronous method calls in one of two ways.

  • Small program mode

    Successful and failed callbacks are passed to handle the two different cases

    wx.showToast({
      title: 'Hello, world'.success: (a)= > console.log('success'),
      fail: (a)= > console.log('failure'})),Copy the code
  • Directing a way

    Pass a callback with an error parameter to verify that the call was successful

    db.find({ name: 'Idan Loo' }, (err, data) => {
      if (err) {
        // Err is the cause of the call failure
        console.log(err)
        return
      }
      // Data is the parameter passed back asynchronously
      console.log(data)
    })
    Copy the code

The two ways have their own strengths. Here we only discuss wechat and Promise of the interface of MongoDB. I believe you can draw a parallel.

Promise to change

Simple implementation

ShowToast, for example

const showToast = option= >
  new Promise((resolve, reject) = >wx.showToast({... option,success: resolve,
      fail: reject,
    })
  )

showToast({ title: 'Hello, Promise' })
  .then((a)= > console.log('success'))
  .catch((a)= > console.log('failure')) 
Copy the code

Now that you know how to Promise the interface of the applet, you just need to repeat the code above and change all the interfaces you need to use to Promise.

A higher level implementation

It’s quick to copy and paste a shuttle, but as a programmer, it’s natural to pursue a cleaner implementation.

As observed, all asynchronous interfaces of applets have the same form and are located in WX objects, so we can abstract the general promisify method to Promise the applets interface

const promisify = name= > option => 
  new Promise((resolve, reject) = >wx[name]({... option,success: resolve,
      fail: reject,
    })
  )

const showToast = promisify('showToast')
const request = promisify('request')
Copy the code

Now just a line of code, you can Promise the interface of the small program, quickly write before the ugly callback code to change over!

More advanced implementations

If you are like me, code cleanliness to the above code can not accept, then congratulations to you, through Proxy can better achieve our goal.

const pro = new Proxy(wx, {
  get(target, prop) {
    return promisify(prop)
  }
})

pro.showToast({ title: 'Hello, world' }).then(...)
pro.request({ url: 'https://github.com' }).then(...)
Copy the code

Now you can use Pro just like WX objects with a proxy based on the promisify method, and all asynchronous methods are promised!

Don’t need to implement

The best implementation is to hand over to others to implement, just as I have already packaged the code in the previous upload, minapp-Promise, less than 1K, out of the box.

It’s not easy to see here, so I hope you can give me a thumbs up and even better, give me a star on GitHub.

Mobile phone code word, if there is a mistake, wan Hope to be corrected.