微信小程序增加ES6的promise特性支,微信小程序新版本中移除了promise的支持,需要自己使用第三方库来自行实现ES6的promise特性,首先下载第三方库Bluebird ,下载地址: Bluebird官网
下载其中一个都可以,未经压缩的 bluebird.js 和已压缩的bluebird.min.js 文件。
在微信小程序中引入第三方库
将下载的文件放在在微信小程序工程目录下的 utils文件夹中,改名为 promise.js 文件,
然后在文件 util.js 中引用 ,并添加其他相关代码
1 var Promise = require("promise.js"); 2 3 const _http = (url, options) => { 4 const method = "POST"; 5 const header = { 'content-type': 'application/json' } 6 return new Promise((resolve, reject) => { 7 let params = { 8 url, method, header, success(res) { 9 resolve(res); 10 }, fail(err) { 11 reject(err); 12 } 13 }; 14 15 if (options) { 16 params = Object.assign(params, options) 17 }; 18 wx.request(params); 19 }) 20 };
使用方式如下:
参考: http://www.51xuediannao.com/xiaochengxu/xiaochengxu_promise.htm