Convert WeChat applet asynchronous API to promise to simplify asynchronous programming

Source: Internet
Author: User
Tags git clone

Convert the applet asynchronous API to promise. How easy it is to handle asynchronous operations with promise, who knows who.
The official does not give the Promise API to handle asynchronous operations, and the official API is very asynchronous, which makes the multi-asynchronous programming layer callback, the code is complex, callback to hit the computer.
A generic tool was written to convert the official asynchronous API into promise, which facilitates processing (multiple) asynchronous operations.

You can use this:

Prepare the transformed method and reveal

// /utils/wx-promise.jsimport toPromise from '/module/to-promise/src/index'const toPromiseWx = toPromsie(wx)export const request = toPromiseWx('requset')export const getLocation = toPromiseWx('getLocation')export const setStorage = toPromiseWx('setStorage')//export 其他你项目中可能用到的异步API

Use in other files
Used in App.js:

//App.jsimport { request } from './utils/wx-promise.js'App({  onLanuch: () => {    request({ url: 'http://api.yourapi.com' })      .then(() => {        //成功后处理      })      .then(() => {        //失败后处理      })  }})

Use in other page:

// /page/index.jsimport { request, setStorage } from '../utils/wx-promise.js'page({  onLoad: () => {    request({ url: 'http://api.yourapi.com' })      .then(() => {        //成功后处理      })      .then(() => {        //失败后处理      })  },  onHide: () => {    setStorage({      key: 'yourkey',      data: 'yourvalue'    })      .then(() => {        //保存成功      })      .then(() => {        //保存失败      })  }})

Project Address: To-promise

Other more specific usage, paste the readme directly, as follows.

to-promiseis a tool library that transforms the applet asynchronous API to Promise

Advantages:

    1. Avoid the problem that too many callbacks caused by the small program's asynchronous programming multiple callbacks lead to unclear logic and too long space.
    2. With the help of promise asynchronous programming features, chained operations are supported, like synchronous write-asynchronously.
    3. The conversion API is almost the same as the official API.

How to use:

    1. Installation
    • Using the git installation to 项目根目录/module ,
git clone github.com/tornoda/to-promise
    • or direct download into the project directory such as:/module
    1. Introduce it where it's needed
import toPromise from '/module/to-promise/src/index'
    1. Bind the Global object ( wx ) to the function so that the API can be taken
const toPromiseWx = toPromise(wx)
    1. Start converting the asynchronous API you need
//apiName为异步方法名,如对wx.request()进行转化const request = toPromiseWx('request')//直接使用request方法

Example:

import toPromise from '/module/to-promise/src/index'//转换wx.getStorage()const getStorage = toPromsie(wx)('getStorage') //使用getStorage({ key: 'test' })  .then(    (res) => {      //res的值与wx.getStorage({ success: (res) => {} })中的res值一样      //res = {data: 'keyValue'}      console.log(res.data)//控制台打印storage中key对于的value      return res.data//如果需要继续链式调用转化后的api,需要把值显示返回    },    (err) => {      //err的值与wx.getStorage({ success: (err) => {} })中的err值一样      throw err    }  )

For the use of promise objects, see promise

Api

    • Topromise (Global)

Parameters

(WX): wx Global object. toPromise(wx)this is called

Return

(function): the parameter (string) is the asynchronous method name of the applet. Returns a function that has the following parameters and return values.

parameter : (object) The object that corresponds to the parameter (object) in the WX applet async method is dropped success fail . For example:

The official wx.getLocation(OBJECT) API OBJECT accepts the following attributes: type altitude success fail complete , then remove ( success fail ) after: type altitude complete .

return : (Pending Promsise) returns an unknown state of the Promise object on which the. then (onfulfilled, onrejected) method is invoked to handle the case of success or failure. Onfulfilled is the callback function called after the request succeeds, the parameter is the return value, onrejected is the callback function after the request failed, the parameter is the returned error message.

In simple terms,

const getLocation = toPromiseWx('getLocation')getLocation({  type: 'wgs84',  altitude: true,  complete: () => { console.log('to-promsise is awesome') }}).then(  (res) => {//dosomething if succeed},  (err) => {//dosomething if failed})

Equivalent to the official call below

wx.getLocation({  type: 'wgs84',  altitude: true,  complete: () => { console.log('to-promsise is awesome') },  success: (res) => {//dosomething if succeed},  fail: (err) => {//dosomething if failed}})

Examples of application scenarios

    1. One-time asynchronous invocation, see API last
    2. Multiple asynchronous operation calls, and each time the next call uses the result of the previous return.
      such as: Obtain GPS information, according to GPS information to obtain weather information, obtain weather information immediately deposited localstorage.
import toPromise from '/module/to-promise/src/index'const toPromiseWx = toPrmise(wx)//方法转换const getLocation = toPromiseWx('getLocation')const request = toPromiseWx('request')const setStorage = toPromiseWx('setStorage')//链式写逻辑getLocation() //获取位置信息  .then(    (res) => { //位置获取成功后的处理,res为返回信息      //处理res后返回有用的信息,这里直接返回res,用于演示      return Promise.resolve(res) //必须    },    (err) => { //位置获取失败后的错误处理,err为错误信息      //错误处理      return Promise.resolve(err) //必须    }  )  .then(    (res) => { //根据位置获取成功后的信息,请求天气信息      return request({ url: 'http://api.weather.com'}) //返回一个pending 状态下的Promise    }  )  .then(    (res) => {  //天气获取成功后存入storage的回调      setStorage({        key: 'test',        data: 'res'      })    },    (err) => {      //天气获取失败后执行这里,err为获取天气失败的错误信息    }  )

If you use the official API to write the above logic, the code is:

  wx.getlocation ({success: (res) = {//some transformation with res wx.request ({url: ' Http://ap          I.weather.com ', Success: (res) = {Wx.setstorage ({success: () = {//do something }, Fail: (Err) = {//do something if Err Happend}}}, fail: (err) = {//do something if Err happend}}, fail: (err) = = {//do something if err happend} //Layer callback, if the logic is more complex point, may be crazy  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.