我有一個異步函式,它請求一個具有 name 和 id 屬性的物件。await axios.get(url).data.name我知道如果不被踢到 catch 陳述句中,您將無法回傳。
我的問題是它不起作用的原因是什么?
async function getConstellationNameById(id) {
const url = `${BASE_URL}/constellations/${id}`;
try {
return await axios.get(url).data.name;
} catch (error) {
throw `Constellation with id of ${id} could not be found.`;
}
}
如果我將 GET 請求存盤在一個變數中,然后使用點表示法訪問它的 name 屬性:
try {
//return axios.get(url).data.name;
const constellation = await axios.get(url);
return constellation.data.name;
}
是因為點符號有時間嗎?因此,當 GET 請求在事件佇列中時,該.data.name部分被視為同步代碼并且無法獲取任何內容?我曾想過,既然它是在一行中執行的,那么屬性訪問器會與 GET 請求一起執行嗎?
還是因為其他原因?
我還認為您只能在.then()and.catch()陳述句中訪問 Promise 物件的屬性;不是這樣嗎?
如果我在學習中濫用任何術語,請提前道歉!只是真的想在繼續之前確保我理解推理。
uj5u.com熱心網友回復:
.優先級高于await,因此您的代碼等效于:
return await (axios.get(url).data.name);
所以axios.get(url).data.name需要一個Promise。但是您要等待的承諾由axios.get(url). 添加括號以強制正確分組:
return (await axios.get(url)).data.name;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/489423.html
標籤:javascript 异步等待 axios 特性 得到
上一篇:在頁面之間傳遞資料反應
