2017-08-01 32 views
1

在控制檯上運行下面的代碼,我得到一個對象數組。使用fetch從API獲取數據,如何在promise解決後訪問數據?

fetch('https://api.github.com/users/chriscoyier/repos') 
    .then(response => response.json()) 
    .then(data => { 
    // Here's a list of repos! 
    console.log(data) 
    }); 

以後如何訪問數據?例如,如果我想console.log數據[0] .archive_url,承諾解決後?但是,這給出了一個錯誤「未捕獲的ReferenceError:數據未定義」。我如何訪問該對象數組?

console

+0

的console.log(數據[0] .archive_url)工作正常,我。 https://jsfiddle.net/dyspkd12/ – Adriani6

+0

將'data'分配給全局變量。 – deceze

+0

@ Adriani6我希望在承諾解決後訪問數據。這隻有在我立即將它放入提取請求時纔有效。 – userden

回答

1
var myGlobalVar; 

fetch('https://api.github.com/users/chriscoyier/repos') 
    .then(response => response.json()) 
    .then(data => { 
    console.log(data); 
    myGlobalVar = data; 
    }); 

一旦這個請求已經完成(一旦你看到控制檯輸出),數據現已在可變myGlobalVar可供您與控制檯上玩。您也可以使用瀏覽器的調試器在回調函數中設置斷點,並從那裏直接訪問data

注意,這不會在實際的代碼工作,這是僅適用於交互式控制檯有用:How do I return the response from an asynchronous call?