javascript - Promise.all 过早解决

标签 javascript es6-promise

<分区>

我想获取多个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 在它的组件 promise 解析之前解析?

我在 Chrome 55 上运行它。

最佳答案

您需要返回 promise :

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 :

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

关于javascript - Promise.all 过早解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41225282/

相关文章:

javascript - 检测字符串上的 html 标签,获取值并删除 javascript 中 html 标签内的值

javascript - HTML 单选输入,带有(必需)文本选项 "other"

javascript - jQuery 缩放效果,缩放 1.1 并在背景位置更改时返回 1

Javascript promise : catch flow

javascript - 同步调用 JavaScript 类方法

javascript - 我无法在Node.js中获得 “result”的值

javascript - 生命游戏内存问题 : 3D Array (generations, x, y)。可以最小化内存使用吗?

javascript - 选项卡上的 Bootstrap 3 数据目标属性不起作用

javascript - 我如何等待多个 Promise.all()

javascript - 处理 Promise 对象中的错误结果的正确方法是什么?