前言
在平常的項(xiàng)目開發(fā)中肯定會(huì)遇到同步異步執(zhí)行的問題,還有的就是當(dāng)執(zhí)行某一個(gè)操作依賴上一個(gè)執(zhí)行所返回的結(jié)果,那么這個(gè)時(shí)候你會(huì)如何解決這個(gè)問題呢;
1.是用settimeout讓它異步執(zhí)行,顯然這只是讓它加入異步任務(wù)隊(duì)列中去執(zhí)行,但并不能保證等待其返回結(jié)果再去執(zhí)行另一個(gè)操作。
2.還是自己封裝callback函數(shù)?那樣就會(huì)陷入所謂的回調(diào)地獄,代碼層層嵌套,環(huán)環(huán)相扣,邏輯稍微復(fù)雜就會(huì)很難去維護(hù)。
3.當(dāng)然es6中的promise倒是很好的解決了這樣的問題,再配合es7的async和await就更完美了,await返回的也是一個(gè)promise對(duì)象,這個(gè)關(guān)于promise和async,await的使用方法就不說了。
實(shí)現(xiàn)方案
首先小程序目前還是不支持es7的async和await的,那么如何讓它支持呢
1、點(diǎn)擊下載
regenerator,并把下載好的runtime.js文件夾放到自己小程序的utils目錄下,包總共才20kb多,體積很小的。
2、在需要調(diào)的地方引入 import regeneratorRuntime from '../../utils/runtime.js'
3、如何封裝并使用
封裝:
const postData = async function(url, data) { wx.showLoading({ title: '加載中', }) let promiseP = await new Promise(function(resolve, reject) { wx.request({ url: baseUrl + url, data: data, method: 'POST', header: { 'content-type': 'application/json', 'access-token': wx.getStorageSync('token') }, success: function(res) { wx.hideLoading(); if (res.statusCode === 200) { resolve(res) } else { reject(res.data) } }, fail: function(err) { wx.hideLoading(); reject(err) if (err.code === 401) {} } }) }) return promiseP}module.exports = { postData}使用:
import regeneratorRuntime from '../../utils/runtime.js';const app = getApp(), postData = require('../../service/koalaApi.js');async demo() { await postData(app.globalData.baseUrl + '/test',{ data: {} }).then((res) => { console.log(res) })}下面進(jìn)行了更完善的一個(gè)封裝,包括各種錯(cuò)誤判斷的處理和簡(jiǎn)化,通過傳參的方式,來靈活調(diào)用
// 當(dāng)前hostconst url_host = require('API.js').host // 當(dāng)前版本const currentVersion = require('util.js').currentVersion // 當(dāng)前路徑import { currentPagePath } from 'util.js' // 調(diào)用fetch方法,然后依次鏈?zhǔn)絺魅?/ url, method, header, data, loading(是否顯示loading) function fetch(url, method, header, data, loading) { // 判斷給服務(wù)端傳遞undefined的問題 let fetchP = new Promise(function (resolve, reject) { if (loading) { wx.showLoading({ icon: 'loading' }) } if(data && data.unionId && typeof data.unionId === "undefined"){ wx.hideLoading() return reject({ ok:false, error: 'unionId -> ' + typeof data.unionId }); } wx.request({ url: url_host + url, method: method ? method : 'GET', header: { 'content-type': 'application/json', // 默認(rèn)值 'version': currentVersion, 'pagePath': currentPagePath() }, data: data, success: function (res) { if (res.statusCode < 500) { resolve(res.data) } else { showError() reject(res.data) } }, fail: function (err) { showError() reject(err) }, complete: function (comp) { if (loading) { wx.hideLoading() } } }) }) return fetchP}// 服務(wù)器開小差了function showError () { wx.hideLoading() // 獲取頭文件路徑 wx.navigateTo({ url: '/pages/serverError/serverError', })}module.exports = { fetch}思考
1、為什么引入regeneratorRuntime,就能夠使用async/await?不需要配合babel嗎?
2、regeneratorRuntime都做了什么?
總結(jié)
1、首先先明白babel和polyfill分別干啥的;
Babel 是一個(gè)廣泛使用的轉(zhuǎn)碼器,Babel 默認(rèn)只轉(zhuǎn)換新的 JavaScript 句法,而不轉(zhuǎn)換新的 API。
例如,Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise 等全局對(duì)象,以及一些定義在全局對(duì)象上的方法(比如 Object.assign)都不會(huì)轉(zhuǎn)譯。
如果想使用這些新的對(duì)象和方法,必須使用 babel-polyfill,為當(dāng)前環(huán)境提供一個(gè)墊片。
2、Polyfill用于實(shí)現(xiàn)瀏覽器并不支持的原生API的代碼。
3、在明白上面的意思之后,還需要明白的是,babel-polyfill是一股腦把全部都給你添加到j(luò)s文件中,而現(xiàn)在的runtime將會(huì)判斷你哪些需要加載的,有選擇性的進(jìn)行加載,并且后者也不會(huì)污染全局變量。在這里regeneratorRuntime最終轉(zhuǎn)化成es6的generator來用的。具體的可以自己去下babel官網(wǎng),輸入相關(guān)代碼可以看下最終轉(zhuǎn)換后的代碼。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選