2017-09-22 38 views
0

我試圖獲取與使用異步讀取和等待這個公共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} )行被執行。

+0

'[對象的對象]'只是因爲你的最終輸出字符串轉換的可能。如果你直接輸出console.log(),你應該看到所需的對象。您不能將對象放入模板文字中並獲取打印出的屬性。另外,'getAnimailInfo()'返回一個承諾。所以,你必須使用'await'或'.then()'來獲得該承諾的價值。 – jfriend00

+0

@ jfriend00 _你不能把一個對象放入模板文字中並獲得打印出來的屬性?你爲什麼這麼認爲? – alexmac

+0

@alexmac:因爲模板文字將其「參數」轉換爲字符串,並且對象的默認字符串表示形式爲「[object Object]」,即不是屬性列表。 –

回答

2

您不能通過這種方式致電console.log(animals.getAnimalInfo('pig'));animals.getAnimalInfo返回一個承諾。爲了得到結果,你應該使用then回調:

const animals = new FetchAnimalApi(); 
animals 
    .getAnimalInfo('pig') 
    .then(result => console.log(result)); 
+0

由於OP在其他地方使用'await',因此答案應該可以提供'await'作爲選項,而不僅僅是'.then()'。 – jfriend00

+0

我想用'async/await'提出一個解決方案,但在這種情況下它沒有意義。創建一個新函數來打印getAnimalInfo()的結果... – alexmac

+0

幫了我一下!但仍然沒有成功):我編輯的問題沒有進一步解釋。 – Anna