javascript - 如何在非async函數下使用await
問題描述
await需要在async函數中使用,所以每次我們想要使用await必須先在async函數中定義,然后調用這個async函數。
就比如這樣
async function fn(){}fn()
詳細一點的例子
async function asy(){ // 獲取當前城市的位置 獲取熱門城市 獲取所有城市 const [resCityGuess,resCityHot,resCityAll]=await Promise.all([ this.http.get(’api/v1/cities?type=guess’), this.http.get(’api/v1/cities?type=hot’), this.http.get(’api/v1/cities?type=group’) ]) this.cityGuessName=resCityGuess.data.name; this.cityGuessId=resCityGuess.data.id; this.cityHot=resCityHot.data; this.cityAll=resCityAll.data;}asy.apply(this);
每次使用await之前都需要多定義一次async然后再調用,這一個過程我覺得略微麻煩以及重復,所以想問下是否存在什么辦法優化或者解決這一問題?
問題解答
回答1:async 可以不需要 await, await 必須依賴 async
回答2:async聲明的函數返回值是Promise對象:
這樣一個函數
async function fn() {}
使用await就需要放在async函數中
async function anthor() { await fn()}
不使用await就當作Promise用
function anthor() { fn().then(...).catch(...)}回答3:
試試這樣
function asy(){ // 獲取當前城市的位置 獲取熱門城市 獲取所有城市 Promise.all([this.http.get(’api/v1/cities?type=guess’),this.http.get(’api/v1/cities?type=hot’),this.http.get(’api/v1/cities?type=group’) ]).then(values =>{this.cityGuessName=resCityGuess.data.name;this.cityGuessId=values[0].data.id;this.cityHot=values[1].data;this.cityAll=values[2].data; });}asy.apply(this);
相關文章:
1. 在mac下出現了兩個docker環境2. css3 - css怎么實現圖片環繞的效果3. android - 用textview顯示html時如何寫imagegetter獲取網絡圖片4. javascript - 原生canvas中如何獲取到觸摸事件的canvas內坐標?5. css - 定位為absolute的父元素中的子元素 如何設置在父元素的下面?6. JavaScript事件7. javascript - jquery hide()方法無效8. 網頁爬蟲 - 用Python3的requests庫模擬登陸Bilibili總是提示驗證碼錯誤怎么辦?9. 注冊賬戶文字不能左右分離10. html - vue項目中用到了elementUI問題
