In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to use Promise for asynchronous operation in WeChat Mini Programs". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use Promise for asynchronous operation in WeChat Mini Programs" can help you solve the problem.
Using Promise for asynchronous process processing in WeChat Mini Programs
We know that JavaScript is executed by a single process, and synchronous operations block the execution of the program. For example, in a browser page program, if a piece of synchronized code needs to be executed for a long time (such as a large loop operation), the page will get stuck.
So, in JavaScript, there are some asynchronous features that provide performance and experience benefits for the program, such as putting code into setTimeout () to execute, or in a web page, we use Ajax to make asynchronous data requests to the server. These asynchronous code will not block the main process of the current interface, the interface can still operate flexibly, wait until the execution of the asynchronous code is completed, and then do the corresponding processing.
A typical piece of asynchronous code looks like this:
Function asyncFunc (callback) {setTimeout (function () {/ / write your logic code / /... / / the logic code ends here and execute a callback function callback ();}, 5000);}
Or:
Function getAccountInfo (callback, errorCallback) {wx.request ({url:'/ accounts/12345', success: function (res) {/ /. Callback (data);}, fail: function (res) {/ /. ErrorCallback (data);});}
Then we call:
AsyncFunc (function () {console.log ("asyncFunc () run complete");}); getAccountInfo (function (data) {console.log ("get account info successfully:", data);}, function () {console.error ("get account info failed");})
This is a way to use callback functions to control the flow of code execution. This looks fine and easy to understand.
However, if we have too many asynchronous operations in a piece of code and want to make sure that these asynchronous operations are executed sequentially, then our code looks very bad, like this:
AsyncFunc1 (function () {/ /... AsyncFunc2 (function () {/ /... AsyncFunc3 (function () {/ /... AsyncFunc4 (function () {/ /... AsyncFunc5 (function () {/ /...});})
Such code readability and maintainability can be imagined. Also, the real problem with callback functions is:
It deprives us of the ability to use keywords such as return and throw.
Is there any way to improve this problem? The answer is yes, the emergence of the concept of Promise solves all this very well. As to what Promise is, I will not copy and paste it here. I will mainly talk about how we use it to solve our problems.
Let's take a look at what Promise would look like in the above example. Let's first turn these functions into Promise:
Function asyncFunc1 () {return new Promise (function (resolve, reject) {/ /...})} / / asyncFunc2,3,4,5 is also implemented in the same way as asyncFunc1.
Then take a look at how they are called:
AsyncFunc1 () .then (asyncFunc2) .then (asyncFunc3) .then (asyncFunc4) .then (asyncFunc5)
In this way, these asynchronous functions will be executed one by one in order.
Promise is natively supported in ES6, but in environments where Promise is not natively supported, we have many third-party libraries to support, such as Q.js and Bluebird. They generally provide not only standard Promise API, but also some standard but very useful API, which makes the control of asynchronous processes more elegant.
From WeChat Mini Programs's API document, we can see that many functions in the JavaScript API provided by the framework are actually asynchronous, such as wx.setStorage (), wx.getStorage (), wx.getLocation (), and so on, which are also the callback handling methods provided. Pass success and fail,complete callback functions in the parameters to deal with success or failure respectively.
Such as:
Wx.getLocation ({type: 'wgs84', success: function (res) {var latitude = res.latitude var longitude = res.longitude var speed = res.speed var accuracy = res.accuracy}, fail: function () {console.error ("get location failed")})
Can we make WeChat Mini Programs's asynchronous API support Promise? The answer is yes, of course we can use Promise to package these API one by one, but this is still troublesome. However, since the parameter format of Mini Program's API is relatively uniform, only one object parameter is accepted, and the callback is set in this parameter, so it is convenient for our unified processing, and we can write a non-invasive tool method to accomplish this work:
Suppose we write this tool method to a file called util.js:
Var Promise = require ('.. / libs/bluebird.min') / / I used bluebird.jsfunction wxPromisify (fn) {return function (obj = {}) {return new Promise ((resolve, reject) = > {obj.success = function (res) {resolve (res)} obj.fail = function (res) {reject (res)} fn (obj)})} module.exports = {wxPromisify: wxPromisify}
After that, let's take a look at how to use this method to change the original callback API into Promise:
Var util = require ('.. / utils/util') var getLocationPromisified = util.wxPromisify (wx.getLocation) getLocationPromisified ({type: 'wgs84'}). Then (function (res) {var latitude = res.latitude var longitude = res.longitude var speed = res.speed var accuracy = res.accuracy}) .catch (function () {console.error ("get location failed")}). That's all for "how to use Promise for asynchronous operations in WeChat Mini Programs". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.