重庆小潘seo博客

当前位置:首页 > 重庆网络营销 > 小潘杂谈 >

小潘杂谈

微信小程序的wx.request与Promise的结合使用

时间:2020-09-05 12:00:08 作者:重庆seo小潘 来源:
这次给大家带来微信小程序的wx.request 与Promise的结合使用,微信小程序的wx.request与Promise结合使用的注意事项有哪些,下面就是实战案例,一起来看一下。 在使用Promise,我的多次异步代码通常是这样的.ajax(url, function (res){ajax(res.url, function(

这次给大家带来微信小程序的wx.request 与Promise的结合使用,微信小程序的wx.request与Promise结合使用的注意事项有哪些,下面就是实战案例,一起来看一下。

在使用Promise,我的多次异步代码通常是这样的.ajax(url, function (res){ajax(res.url, function(res) {ajax(res.url, function(res) {if (res.status == '1') {ajax(res.url, function(res) {...}}else if (res.status == '2') {ajax(url2, function(res) {...}...}}});这种流程是很耗费心力并且脆弱的,体验很糟糕,因此,在这次小程序的开发中为了更好的体验,我开始使用了Promise.

代码如下,这样一来,当我们第二个请求需要第一个参数判断时,可以不再陷入回调地狱,// 小程序与后端情求接口let baseUrlPromise = 'https://xxx.com';// 定义方法返回Promise参数,obj 为wx.request 方法中所需参数let req = function (obj) {return new Promise(function (resolve, reject) {wx.request({url: baseUrlPromise + obj.url,data: obj.data,header: obj.header,method: obj.method == undefined ? "get" : obj.method,success: function (data) {// 回调成功执行resolveresolve(data)},fail: function (data) {// 回调失败时if (typeof reject == 'function') {reject(data);} else {console.log(data);}},})})}// 执行req 方法,传入第一个请求,let req1 = req({url: '第一次请求链接,与baseUrlPromise 相结合',data: {},})// 当需要多次请求时加入req1.then(function (data) {console.log('promiseThen1')console.log(data);return req({url: '第二次请求链接',})}).then(function (data) {console.log('promiseThen3')console.log(data);return req({url:'第三次请求链接'})}).then(......).catch(function(data){console.log(PromiseCatch)})相信看了本文案例你已经掌握了方法,更多精彩请关注小潘博客其它相关文章!

推荐阅读:

Vue指令的使用

JS闭包的使用以上就是微信小程序的wx.request与Promise的结合使用的详细内容,更多请关注小潘博客其它相关文章!