为什么不能直接从Fetch API的响应中访问JSON?

时间:2019-05-09 04:46:30

标签: javascript fetch

在下面的示例中,为什么第一次提取未收到预期的json?您如何才能抓取处理多种内容类型,例如application/jsonimage/jpeg

// outputs: {}
fetch(url)
.then(function(response){
   alert(JSON.stringify(response.json()));
});

// outputs the expected json
fetch(url)
.then(function(response){ return response.json(); })
.then(function(data){ alert(JSON.stringify(data)) });

1 个答案:

答案 0 :(得分:2)

response.json()不同步。当系统运行并解析JSON时,它将返回一个Promise。

第二个示例起作用的原因是,当您在承诺中返回承诺时,外部承诺会等待内部承诺解决。