Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to convert WeChat Mini Programs Asynchronous API to Promise

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to convert WeChat Mini Programs asynchronous API into Promise". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to convert WeChat Mini Programs asynchronous API into Promise".

Convert WeChat Mini Programs asynchronous API to Promise, simplify asynchronous programming, bid farewell to layers of callbacks... convert WeChat Mini Programs asynchronous API to Promise. Who knows how convenient it is to handle asynchronous operations with Promise.

Wechat officially does not provide Promise API to handle asynchronous operations, and the official API is very asynchronous, which makes multi-asynchronous programming layers of callbacks, a complex code, callbacks want to hit the computer.

So I wrote a general tool that converts Wechat's official asynchronous API into Promise, which makes it easy to handle (multiple) asynchronous operations.

You can use it like this:

Prepare the transformed method and expose

/ utils/wx-promise.js

Import 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 other asynchronous API that you may use in your project

Use in other files

Use in App.js:

/ / App.js

Import {request} from'. / utils/wx-promise.js'

App ({

OnLanuch: () = > {

Request ({url: 'http://api.yourapi.com'})

.then () = > {

/ / successful post-processing

})

.then () = > {

/ / Post-processing of failure

})

}

})

Use in other page:

/ page/index.js

Import {request, setStorage} from'.. / utils/wx-promise.js'

Page ({

OnLoad: () = > {

Request ({url: 'http://api.yourapi.com'})

.then () = > {

/ / successful post-processing

})

.then () = > {

/ / Post-processing of failure

})

}

OnHide: () = > {

SetStorage ({

Key: 'yourkey'

Data: 'yourvalue'

})

.then () = > {

/ / saved successfully

})

.then () = > {

/ / failed to save

})

}

})

Project address: to-promise

For more specific uses, paste README directly, as follows.

To-promise is a tool library that converts WeChat Mini Programs's asynchronous API to Promise.

Advantages:

Avoid too many callbacks caused by Mini Program asynchronous programming, such as unclear logic, too long space and so on.

With the help of the characteristics of Promise asynchronous programming, it supports chain operation and writes asynchronism like synchronization.

The converted API is almost the same as the official API of Wechat.

How to use it:

Installation

Install to the project root directory / module using git

Git clone https://github.com/tornoda/to-promise

Or download it directly and put it in the project directory, such as / module

Introduce where it is needed

Import toPromise from'/ module/to-promise/src/index'

Bind the Wechat global object (wx) to the function so that you can get the API from Wechat.

Const toPromiseWx = toPromise (wx)

Start converting the asynchronous API you need

/ / apiName is the Wechat asynchronous method name, such as converting wx.request ()

Const request = toPromiseWx ('request')

/ / use the request method directly

For example:

Import toPromise from'/ module/to-promise/src/index'

/ / convert wx.getStorage ()

Const getStorage = toPromsie (wx) ('getStorage')

/ / use

GetStorage ({key: 'test'})

.then (

(res) = > {

The value of / / res is the same as the res value in wx.getStorage ({success: (res) = > {}})

/ / res = {data: 'keyValue'}

Console.log (res.data) / / console prints the value of key in storage

If return res.data// needs to continue to chain call the converted api, it needs to display and return the value.

}

(err) = > {

The value of / / err is the same as the err value in wx.getStorage ({success: (err) = > {}})

Throw err

}

)

For the use of Promise objects, see Promise

API

ToPromise (global)

Parameters.

(wx): wx global object. That is, toPromise (wx) calls

Return

(function): the parameter (string) is the Mini Program asynchronous method name. Returns a function whose arguments and return values are as follows.

Parameter: (object) corresponds to the parameter in the wx Mini Program asynchronous method (OBJECT) the object after removing success and fail. For example:

The OBJECT of the official APIwx.getLocation (OBJECT) accepts the following attribute: type altitude success fail complete, so after success fail it is: type altitude complete.

Return: (pending Promsise) returns a Promise object with an unknown state on which the .then (onFulfilled, onRejected) method is called to handle the success or failure of the counterpart. OnFulfilled is the callback function called after a successful request, and the parameter is the return value. OnRejected is the callback function after the request fails, and the parameter is the returned error message.

To put it simply,

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}

)

Is equivalent to the following official call

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

For a single asynchronous call, see API Last

Multiple asynchronous operation calls, and each call uses the result returned by the previous one.

For example: after obtaining the GPS information, get the weather information according to the GPS information, and store it in localStorage immediately after obtaining the weather information.

Import toPromise from'/ module/to-promise/src/index'

Const toPromiseWx = toPrmise (wx)

/ / method conversion

Const getLocation = toPromiseWx ('getLocation')

Const request = toPromiseWx ('request')

Const setStorage = toPromiseWx ('setStorage')

/ / chain write logic

GetLocation () / / get location information

.then (

(res) = > {/ / the processing after the location is obtained successfully. Res is the returned information.

/ / useful information is returned after processing res. Here, res is returned directly for demonstration

Return Promise.resolve (res) / / must

}

(err) = > {/ / error handling after failed position acquisition. Err is the error message.

/ / error handling

Return Promise.resolve (err) / / must

}

)

.then (

(res) = > {/ / request weather information according to the location

Return request ({url: 'http://api.weather.com'}) / / returns a Promise in pending status

}

)

.then (

(res) = > {/ / callback stored in storage after successful weather

SetStorage ({

Key: 'test'

Data: 'res'

})

}

(err) = > {

/ / execute here after the weather acquisition failed. Err is used to obtain the error message of weather failure.

}

)

If you write the above logic using the official API, the code looks like this:

Wx.getLocation ({

Success: (res) = > {

/ / some transformation with res

Wx.request ({

Url: 'http://api.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

})

/ / callbacks layer by layer. If the logic is more complicated, it may go crazy.

Thank you for your reading, the above is the content of "how to convert WeChat Mini Programs asynchronous API into Promise". After the study of this article, I believe you have a deeper understanding of how to convert WeChat Mini Programs asynchronous API into Promise, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report