我試圖獲取與使用異步讀取和等待這個公共API,但獲取方法返回一個[目標對象]:使用與異步讀取/等待回報的翻譯:
I類」使用來獲取API:開始
class FetchAnimalApi {
async getAnimalInfo(animal) {
const request = await fetch(`http://my_api_url.com/${animal}`);
const response = await request.json();
return `${animal} goes like ${response.sound}`;
}
}
該API返回的結構(如果該動物是豬):
{"color": "pink", "sound": "roinc"}
我輸入我的類在另一個文件中,把它作爲:
const animals = new FetchAnimalApi();
console.log(animals.getAnimalInfo('pig'));
那麼,我做錯了什麼?
編輯:
現在我的console.log()正好說明了我想打印什麼,但是當我返回響應,我仍然得到[對象對象]:
function getInfo() {
const animals = new FetchAnimalApi();
return animals.getAnimalInfo('pig').then(result => result);
}
雖然調試,我意識到[object object]正在打印在我的屏幕上後const request = await fetch(
http://my_api_url.com/ $ {animal} )
行被執行。
'[對象的對象]'只是因爲你的最終輸出字符串轉換的可能。如果你直接輸出console.log(),你應該看到所需的對象。您不能將對象放入模板文字中並獲取打印出的屬性。另外,'getAnimailInfo()'返回一個承諾。所以,你必須使用'await'或'.then()'來獲得該承諾的價值。 – jfriend00
@ jfriend00 _你不能把一個對象放入模板文字中並獲得打印出來的屬性?你爲什麼這麼認爲? – alexmac
@alexmac:因爲模板文字將其「參數」轉換爲字符串,並且對象的默認字符串表示形式爲「[object Object]」,即不是屬性列表。 –