有時 需要把異步返回的結果當條件來進行判斷。所以 把異步變同步
使用Promise 配合 async 和 awit
// 提交數據
//async關鍵詞
async submit(e) {
var that = this,file_url = '';
//res為上方法請求返回的res.data內容
var res = await that.uploadimg(that.data.ImgsArr[0])
wx.request({
url: httpsRequest.httpsUrl + resHttp.feedback,
data: {},
method: "post",
header: {
'content-type': 'application/x-www-form-urlencoded',
"requesttype": "wxapp",
"token": that.data.tokens
},
success(res) {
console.log(res);
wx.showToast({
title: res.data.msg,
icon: 'success'
})
}
})
},
//圖片上傳
uploadimg:function(a){
var tt = this
return new Promise((resolve, reject) =>{
wx.uploadFile({
filePath: a,
name: 'file',
url: httpsRequest.httpsUrl + resHttp.fileImgIsVideo,
header: {
"content-type": "application/x-www-form-urlencoded",
"requesttype": "wxapp",
"token": tt.data.tokens
},
success(res) {
//resolve作用提示小程序請求已結束
resolve(JSON.parse(res.data))
},
fail (err) {
reject(err)
}
});
});
},
如果有心,在微信小程序官方文檔中搜索 async 可以找到“工具⇒開發輔助⇒代碼編譯”頁面中提到了對 async/await 的支持情況,是在“增加編譯”小節的一個表格中,摘錄一段:
總之呢,就是,只要把“微信開發者工具”更新到 v1.02.1904282 以上,就不需要干 npm install regenerator 這之類的事情,只需要修改一個配置項就能使用 async/await 特性了。這個配置就在“工具欄⇒詳情⇒本地設置”頁面中。
為了快速驗證 async/await 可用,在 app.js 的 onLaunch() 事件函數中加一段代碼:
(async () => {
const p = await new Promise(resolve => {
setTimeout(() => resolve("hello async/await"), 1000);
});
console.log(p);
})();
在短暫的自動編譯運行之后,在調試器界面的 Console 頁簽中可以看到輸出:
hello async/await