微信小程序增加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