在下面的示例中,为什么第一次提取未收到预期的json?您如何才能抓取处理多种内容类型,例如application/json
和image/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)) });
答案 0 :(得分:2)
response.json()
不同步。当系统运行并解析JSON时,它将返回一个Promise。
第二个示例起作用的原因是,当您在承诺中返回承诺时,外部承诺会等待内部承诺解决。