vue中then后的返回值解析
then后的返回值
Promise 中處理的是異步調(diào)用,異步調(diào)用是非阻塞式的,在調(diào)用的時(shí)候并不知道它什么時(shí)候結(jié)束,也就不會(huì)等到他返回一個(gè)有效數(shù)據(jù)之后再進(jìn)行下一步處理
可以使用 async 和 await來得到我們的返回值
在vue 中的函數(shù)加上async
async del(id){ ? ? ? var that=this ? ? ? ? ? ? ?var params={ ? ? ? ? ? ? ? sensorCommonId:id ? ? ? ? ? ? } ? ? ? ? ? ?return ?DelSensorCommonInfo(params).then(function(res) { ? ? ? ? ? ? ? return Promise.resolve(res.data.Data); ? ?? ? ? ? ? ? ? }); ? ? ? ? ? ?? ? ? },
在我們調(diào)用所在的函數(shù)中也加上 async 在調(diào)用del函數(shù)時(shí)
async ?more(){ ? ? ? ?var index= await that.del(array[i].SensorCommonId) ? ? ? ? ? console.log(index) ? }
?? ?function getSomething() { ? ? return "something"; } ? async function testAsync() { ? ? return Promise.resolve("hello async"); } ? async function test() { ? ? const v1 = await getSomething(); ? ? const v2 = await testAsync(); ? ? console.log(v1, v2); } ? test();
獲取.then()中的返回值
以上傳文件到阿里云為例:
export function uploadObj({ file }, type) { ? let name = `路徑名/${Date.parse(new Date()) + file.uid}`; //定義唯一的文件名 ? const fileName = type == 'excel' ? name + ".xlsx" : name; ? const ContentType = type == 'excel' ? "text/xml" : "image/jpeg"; ? new OSS(conf).put(fileName, file, { ? ? ContentType: ContentType ? }).then(({ res, url }) => { ? ? if (res && res.status == 200) { ? ? ? this.$message.success("上傳成功"); ? ? ? return url ? ? } ? }).catch(() => { ? ? this.$message.error("上傳失敗"); ? }); }
以上代碼能實(shí)現(xiàn)上傳圖片/excel到阿里云服務(wù)器,上傳成功后,阿里云服務(wù)會(huì)返回一個(gè)URL。此時(shí)如果直接return url,那么收到的url是undefined。
解決方法如下
export function uploadObj({ file }, type, callback) { ? let name = `路徑名/${Date.parse(new Date()) + file.uid}`; //定義唯一的文件名 ? const fileName = type == 'excel' ? name + ".xlsx" : name; ? const ContentType = type == 'excel' ? "text/xml" : "image/jpeg"; ? new OSS(conf).put(fileName, file, { ? ? ContentType: ContentType ? }).then(({ res, url }) => { ? ? if (res && res.status == 200) { ? ? ? this.$message.success("上傳成功"); ? ? ? callback(url) ? ? } ? }).catch(() => { ? ? this.$message.error("上傳失敗"); ? }); }
調(diào)用此方法
this.uploadObj({ file }, "excel", url => this.importData(url)); ?
傳入的第三個(gè)參數(shù)是回調(diào)函數(shù),這樣在importData方法中,就可以直接獲取到url啦
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue單個(gè)元素綁定多個(gè)事件問題(例如點(diǎn)擊綁定多個(gè)事件方法)
這篇文章主要介紹了vue單個(gè)元素綁定多個(gè)事件問題(例如點(diǎn)擊綁定多個(gè)事件方法),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04vue實(shí)現(xiàn)用v-bind給src和href賦值
這篇文章主要介紹了vue實(shí)現(xiàn)用v-bind給src和href賦值,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04Vue的export?default和帶返回值的data()及@符號的用法說明
這篇文章主要介紹了Vue的export?default和帶返回值的data()及@符號的用法說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Vue實(shí)現(xiàn)Header漸隱漸現(xiàn)效果的實(shí)例代碼
這篇文章主要介紹了Vue實(shí)現(xiàn)Header漸隱漸現(xiàn)效果,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11