vue中then后的返回值解析
then后的返回值
Promise 中處理的是異步調(diào)用,異步調(diào)用是非阻塞式的,在調(diào)用的時候并不知道它什么時候結(jié)束,也就不會等到他返回一個有效數(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ù)時
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("上傳失敗");
? });
}以上代碼能實現(xiàn)上傳圖片/excel到阿里云服務(wù)器,上傳成功后,阿里云服務(wù)會返回一個URL。此時如果直接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)); ? 傳入的第三個參數(shù)是回調(diào)函數(shù),這樣在importData方法中,就可以直接獲取到url啦
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue中使用vue-count-to(數(shù)字滾動插件)詳細(xì)教程
這篇文章主要給大家介紹了關(guān)于Vue中使用vue-count-to(數(shù)字滾動插件)的相關(guān)資料,最近需要開發(fā)一個數(shù)字滾動效果,在網(wǎng)上找到一個關(guān)于vue-countTo的插件,覺得這個插件還不錯,需要的朋友可以參考下2023-09-09
Vue.js使用axios動態(tài)獲取response里的data數(shù)據(jù)操作
這篇文章主要介紹了Vue.js使用axios動態(tài)獲取response里的data數(shù)據(jù)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
vue中 router.beforeEach() 的用法示例代碼
導(dǎo)航守衛(wèi)主要是通過跳轉(zhuǎn)或取消的方式守衛(wèi)導(dǎo)航,本文通過示例代碼講解vue中 router.beforeEach() 的用法,感興趣的朋友跟隨小編一起看看吧2023-12-12

