2017-09-18 61 views
2

我有这样的代码:取的NodeJS承诺回调未决

fetch(url).then(response => { 
    const json = response.json(); 
    console.log('simplest possible fetch', json, json.where); 
}); 

在控制台中我得到:

simplest possible fetch Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} undefined 

我得到这个的时间。有时我会获得“成功”的地位。对我来说,这意味着回调在获取承诺解决之前正在运行。

我希望函数只在抓取完成时才能运行。我该怎么做呢?

回答

9

response.json()返回一个承诺,使用then回调来获取数据:

身体混入的JSON()方法接受一个响应流,并读完成。它返回一个承诺,将解析正文文本的结果解析为JSON。

fetch(url) 
    .then(response => response.json()) 
    .then(data => console.log('simplest possible fetch', data, data.where)); 
+0

真棒答案亚历克斯! :) @alexmac – turmuka