Fetch()2 JSON然后()传递给函数

时间:2017-09-07 05:46:44

标签: javascript json ecmascript-6 fetch

我试图绘制图表。出于显而易见的原因,图形函数最后执行。

数据来自不同的网站。相当快(sourcex)和一个人在不知名的地方(或者看起来如此)(sourcey)。

所以datax来自sourcexdatay来自sourcey。在通过我的脚本运行之前,需要返回两个json。我尝试了以下和多种变化无济于事。

我可以在datay上添加datax。{/ p>

请帮忙。

var datay;
var datax;

fetch(urlx)
.then(function(response) {
  return response.blob();
})
.then(function(myBlob) {
  res=>res.json()
})
.then((out)=>{
  datax=out;
}
.then(fetch(urly)).then(res=>res.json())
.then((out)=>{
 datay=out;
 runThroughScript(datax,datay);
})
.catch(err=>console.log(err));

1 个答案:

答案 0 :(得分:2)

  

我可以在datay上添加datax。{/ p>

它不在您提供的代码中,因此有两个答案:

如果datay确实依赖于datax

您使用链条。您至少有两个选项:嵌套或Promise.all

嵌套:

fetch(urlx)
.then(res => res.json())
.then(datax => {
    // Presumably use `datax` here for something
    return fetch(urly)
        .then(res => res.json())
        .then(datay => {
            runThroughScript(datax, datay);
        });
})
.catch(err=>console.log(err));

Promise.all

fetch(urlx)
.then(res => res.json())
.then(datax => {
    // Presumably use `datax` here for something
    return Promise.all([
        datax,
        fetch(urly).then(res => res.json())
    ]);
})
.then(([datax, datay]) => { // Note destructuring
    runThroughScript(datax, datay);
});
.catch(err=>console.log(err));

请注意,我们将非承诺传递给Promise.all作为第一个数组元素。没关系,它只是按原样传递给结果。

dataydatax是独立的,如问题

所示

您可以使用Promise.all。你传递了一个承诺数组,它会在任何一个拒绝时立即拒绝,或者用它们的分辨率数组(按顺序)解析。见评论:

Promise.all([
    // The first fetch
    fetch(urlx)
    .then(res => res.json())
    ,
    // The second fetch runs in parallel
    fetch(urly)
    .then(res=>res.json())
])
.then(([datax, datay]) => {     // Note the destructured parameters
    runThroughScript(datax, datay);
})
.catch(err=>console.log(err));

(我已经删除了那个显然只是问题中的错误的blob部分。)