Promise.all过早解决

时间:2016-12-19 14:55:12

标签: javascript es6-promise

我想要fetch多个JSON文件。这是我的代码:

var timestamps = [];
var urls = ['assets/layouts/default.json','assets/layouts/simple.json'];
var jsons = [];
Promise.all(urls.map(url => {
  fetch(url)
  .then(data => data.json())
  .then(json => {
    jsons.push(json);
    timestamps.push(performance.now());
  });
}))
.then(() => {
  console.log(`All assets loaded. Assets were loaded at: ${timestamps}, this log was made at ${performance.now()}. Loaded data: ${jsons}`);
}
);

问题在于Promise.all似乎过早地解决了。正如您所看到的,我包含了一些调试,它会记录下来:

All assets loaded. Assets were loaded at: , this log was made at 37.73. Loaded data: 

如果我将console.log包裹在setTimeout中并节省Promise.all被解决的时间,请执行以下操作:

.then(() => {
  let promiseResolvedAt = performance.now();
  setTimeout(() => {
    console.log(`All assets loaded. Assets were loaded at: ${timestamps}, Promise.all was resolved at ${promiseResolvedAt}. Loaded data: ${jsons}`);
  })
}

我明白了:

All assets loaded. Assets were loaded at: 63.44000000000001,63.555, Promise.all was resolved at 55.96500000000001. Loaded data: [object Object],[object Object]

我可以通过使用setTimeout让它像我想要的那样工作,但我确信有更好的方法,我只是在这里做错了。

为什么Promise.all在它的组件承诺解决之前解决了?

我在Chrome 55上运行它。

2 个答案:

答案 0 :(得分:1)

在映射网址数组时,您需要将调用返回到fetch,否则Promise.all(...)正在等待[undefined, undefined],这会立即解决,正如您所观察到的那样。

Promise.all(urls.map(url => {
   return fetch(url)
// ^^^^^^
    .then(data => data.json())
    .then(json => {
      jsons.push(json);
      timestamps.push(performance.now());
    });
}))

答案 1 :(得分:1)

你需要回复承诺:

Promise.all(urls.map(url => {
  return fetch(url)
    .then(data => data.json())
    .then(json => {
      jsons.push(json);
      timestamps.push(performance.now());
    });
}))

来自https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body

  

箭头功能可以有一个简洁的身体"或通常的"块   体"

     

在一个简洁的正文中,只需要一个表达式,一个隐含的表达式   返回附上。 在块体中,您必须使用明确的return   声明