久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

javascript - 如何在非async函數下使用await

瀏覽:125日期:2023-09-20 10:52:43

問題描述

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);

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 祁连县| 清河县| 博白县| 丹东市| 宽甸| 如皋市| 亚东县| 新闻| 修水县| 峡江县| 沈阳市| 阳山县| 上虞市| 香港 | 西宁市| 泗洪县| 平阳县| 抚顺县| 大埔区| 荔浦县| 平泉县| 楚雄市| 安泽县| 四川省| 望江县| 平果县| 高台县| 乌拉特中旗| 内丘县| 霍州市| 瑞安市| 泰宁县| 寿光市| 湖北省| 堆龙德庆县| 泾川县| 宾川县| 湛江市| 太湖县| 德化县| 湘西|