【问题标题】:Fetch() 2 JSONs then() pass to functionFetch() 2 JSONs then() 传递给函数
【发布时间】:2018-02-15 17:45:37
【问题描述】:

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

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

所以datax 来自sourcexdatay 来自sourcey。两个 json 都需要返回,然后才能通过我的脚本运行。我尝试了以下多种变体均无济于事。

我可以添加datay 依赖于datax

请帮忙。

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));

【问题讨论】:

  • 您不能同时回复.blob().json()
  • 我不知何故错过了问题中的声明 "May I add datay is depedant on datax.",因为datay 不是 i> 依赖于问题代码中的datax,我的回答好像它们是独立的。我现在已经确定了答案。

标签: javascript json ecmascript-6 fetch


【解决方案1】:

我可以添加datay 依赖于datax

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

如果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));

请注意,我们将 non-promise 作为第一个数组元素传递给 Promise.all。没关系,它会按原样传递给结果。

如果dataydatax如题所示是独立的

您会为此使用Promise.all。你向它传递一组承诺,一旦他们中的任何一个拒绝,它就会拒绝,或者用他们的一系列决议来解决(按顺序)。见 cmets:

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 部分。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2014-07-13
    • 2020-03-17
    • 1970-01-01
    • 2021-12-27
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多