Detailed explanation use promise to optimize function processing in the JS script of WeChat applets.

In our traditional JavaScript development function, we are used to the processing of the callback function, but with the increase in the callback function, the code is increasingly difficult to read, so the birth of Promise To optimize the demand for JS function processing, introducing promise can solve problems such as readability of asynchronous callback functions, but also makes our code is simple, this article describes how to use Promise in the jujie JS code. Package some functions.

1, the tradition of the small program

For example, we generate a small program, which automatically has a getUserinfo function in the app.js inside, this is Use the traditional mode callback function.

// app.jsapp ({ONLAUNCH: Function () {// Call API Get Data Var logs from the local cache = wx.getStorageSync (‘logs’) | | [] Logs.unshift (Date.Now ()) WX.setStorageSync (‘logs’, logs)}, getUserInfo: Function (CB) {var this = this if (this.globalData.usefo) {typeof cb == ” Function “&& CB (this.globalData.userInfo)} else {// call login interface wx.login ({successuserinfo ({Success: function (res) {That.globalData.userInfo = Res. Userinfo typeof cb == “functioN “&& CB (That.globalData.userInfo)}}}}}}}})}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
   
This By being processed by incoming a CB’s callback function, it is necessary to further determine if the type is function: TypeOf CB == “function”, this processing is still relatively easy to understand.
However, if we have a code, there are too many asynchronous operations, but also to ensure that these asynchronous operations are executed, then our code looks very bad, just like this extreme situation:

AsyncFunc1 (function () {// … asyncfunc2 (function () {// … asyncfunc3 (function () {// … asyncfunc4 (file () {// … asyncFunc5 (function () {// …});});});};});
 If we use Promise Treatment, then a layer of simple packaging can be performed.   
function asyncfunc1 () {Return New Promise (Function (resolve, reject) {// …}) }

2, the use of PROMISE
  Promise is relatively simple, we can refer to the relevant introduction with reference: Getting started with a peak promiseIf we introduce it in the JS function, we need to include the corresponding JavaScript component  
We can download the corresponding component JS on GitHub, introduce a small program project: ES6-Promise
We create a secondary utils.js in the project, then introduced into the PROMISE script, as shown below.

const promise = Require (‘./ promise’)

then in app.js, we modified The original GetUserinfo function is as follows

// app.jsconst utils = request (‘./ utils / util.js’) app ({onlinech: function () {// Call the API to get data Var logs from the local cache = wx.getStorageSync (‘logs’) || [] logs.unshift (Date.Now ()) wx.setStorageSync (‘logs’, logs)}, getuserInfo () {Return New utils.promise (resolve, reject) => {if (this.globaldata.userinfo) {resolve (this.globaldata.userinfo)} Return Utils.getuserinfo (). Then (res => {resolve (this.globaldata). Userinfo = res. userinfo)})})}, // Get System Information GetSystemInfo () {return new utils.Promise ((resolve, reject) => {var that = this if (that.globalData.systemInfo) {resolve (that.globalData.systemInfo)} else {wx.getSystemInfo ({success: function (RES) {Resolve (That.globalData.systeminfo = res);}})}}}}}})}}}}}}}}}}}}}}}})}}}}}}}}}}}}}}}}}}}}}}}}}}}}})}}}}} GlobalData: {UserInfo: Null, SystemInfo: null}, utils})
   We see all the original functions, if we need to introduce ProMise processing, add a layer of function. 
Return new utils.promise (resolve, reject) => {// original function code});

 When we call us, use the THEN function to process, similar to the following code.   
GetUserInfo (). THEN (User => this.SetData). Catch (console.log);

After introducing this promise, we can put some common functions in Utils.js in order to further implement the code, so you can realize the reuse of the code.
 // User Login Function Login () {Return New Promise ((Resolve, Reject) => wx.login ({Success: resolve, fail: reject})} // Get user information Function getUserInfo () {return login (). Then (resolve, reject) => wx.getuserinfo ({Success: resolve, fail: reject}))}   
Function Requstget (URL, DATA) {Return Requst (URL, ‘GET’, DATA)} Function RequstPost (URL, DATA) {Return Requst (URL, ‘POST’, DATA)} // Package Request Request Method Function Requost (URL, Method, Data =}) {wx.ShownavigationBarloading () data.method = Method Return New Promise (resove, reject) = > {wx.Request ({URL: URL, DATA: DATA, HEADER: {} (), // Options, Get, Head, POST, PUT, DELETE, TRACE, CONNECT SUCCESS: FUNCTION (RES ) {wx.hidENAVIGATIONBARLoading () resove (res. dc) {Console.log (‘Reqest Error’, MSG) wx.hidenavigationBarloading () Reject (‘fail’)}}}}}}

The corresponding interface is then released for use in other modules.
  // Published Interface Module.exports = {Promise, MakeArray, GetUserInfo, Get: Requostget, Post: Requstpost, Requst, Decodehtml, Formattime, Getdatediff}  
After packaging these common methods, we call them in the page, the calling code is as follows (the presentation code acquires data from the address, and binds to the interface)

// Use the COMPRISE package function to show Var URL = ‘http: // localhost: 27206 / api / framework / information / findbycode’; var companyURL = http: //www.iqidi.com “; var json = {code: ‘Company’}; app.utils.get (URL, JSON) .Then (Function (RES) {var Data = {URL: CompanyURL, Image: Res. Picture, Content: Res.Content}; THAt.SetData ({Item: Data}); wxparse.wxparse (‘Content’, ‘HTML’, DATA.CONTENT, THAT, 25);});
   
And if we use the original function, the implementation code is as follows.
// Use the standard WX.Request function to display VAR URL = ‘http: // localhost: 27206 / API / framework / information / FindBycode’; var companyURL = “http://www.iqidi.com”; var json = {code: ‘Company’}; wx.Request ({URL: URL, DATA: JSON, SUCCESS: Function (res) {console.log (res); Var Data = {URL: CompanyURL, Image: Res. Data.Picture, Content: res. {{{{{{{i i {}}); wxparse.wxparse (‘Content’, ‘HTML’, DATA. Content, That, 25);}})
 If the function processing of the complex flow is handled, it will be more simple to read using the promise.   
The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Clouds.
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment