[英]Why does this arrow function return a Promise{<pending>}
[英]Why does my async function always return a pending promise?
當我 console.log(data) 時,我記錄了我需要的信息,但是如果在 getWeather() 中返回數據的值,它只會返回一個掛起的 promise。 我嘗試了很多東西,但到目前為止都沒有奏效。 我將在下面留下我損壞的代碼。
const axios = require('axios');
const getWeather = async () => {
try {
let response = await axios.get(
'http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={apiKey}'
);
let data = response.data;
return data;
} catch (e) {
console.log(e);
}
};
async function returnAsync() {
const x = await getWeather();
return x;
}
console.log(getWeather()); // returns a pending promise
console.log('check ', returnAsync()); // also returns a pending promise
async
函數必須返回 promise。 (他們隱式返回Promise<void>
而不是void
!)
異步函數總是返回 promise。 如果異步 function 的返回值不是顯式 promise,它將隱式包裝在 promise 中。
例如,以下內容:
async function foo() { return 1 }
...相當於:
function foo() { return Promise.resolve(1) }
//const getWeather = async () => {...
異步函數的返回值將是 Promise,它將使用異步 function 返回的值解析,或者被異步 ZC1C425268E17385D1AB504F14F 拋出的異常或未捕獲的異常拒絕。
在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function查看更多信息
這可能與您嘗試在同步 function 內部調用異步 function 的事實有關。 這是一個很常見的錯誤,所以不要擔心。 通常,如果您考慮結構,從技術上講,控制台日志可以在異步 function 完成之前運行。 這就是為什么我們有“回調函數”,它基本上只在異步返回值時運行。
Axios 有一個非常巧妙的方法來使用這些回調,它只是使用 .then .then()
function。
所以試試這個,看看它是否有效:
const axios = require('axios');
const getWeather = async () => {
axios.get('http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={apiKey}')
.then(json => console.log(json))
.catch(error => console.log(error))
};
getWeather();
因為您嘗試在異步 function 中調用 get 請求,所以您無法在同步 function 中獲取數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.