简体   繁体   English

arrays(Promise.all or for..of)的异步处理

[英]Asynchronous processing of arrays (Promise.all or for..of)

I know there is a lot of information on this and I have read several articles, but I am still wandering.我知道有很多关于这方面的信息,我已经阅读了几篇文章,但我仍在徘徊。

I have an array of HTTP request urls.我有一组 HTTP 请求网址。 The order of each element in the array is very important.数组中每个元素的顺序非常重要。 I want to get a response by fetching these request urls, and put the responses in the same order as the original array.我想通过获取这些请求 url 来获得响应,并将响应以与原始数组相同的顺序放置。

Below is the code I wrote.下面是我写的代码。 I thought it was right to use promise.all.我认为使用 promise.all 是对的。 We found promise.all to process arrays in parallel, but ordering is not guaranteed.我们发现 promise.all 可以并行处理 arrays,但不能保证订购。 (Is this correct?) (这个对吗?)

const getAllImagePaths = async urls => {
  let copyPaths = [];

  try {
    const data = await Promise.all(urls.map(url => fetch(url)));

    for (let item of data) {
      const { url } = item;
      copyPaths.push(url);
    }

    return copyPaths;
  } catch (err) {
    const { response } = err;

    if (response) alert(MESSAGES.GET_PHOTOS_FAIL);
  }
};

So I modified the code by using the for..of statement.所以我使用 for..of 语句修改了代码。

const getAllImagePaths = async urls => {
  let copyPaths = [];

  try {
    for(let url of urls) {
      const res = await fetch(url);
      const json = await res.json();
      const data = json.parse();

      const { url } = data;

      copyPaths.push(data);
    }

    return copyPaths;
  } catch (err) {
    const { response } = err;

    if (response) alert(MESSAGES.GET_PHOTOS_FAIL);
  }
};

However, when the for of statement is used, the response type of the data is 'cors'.但是,当使用for of 语句时,数据的响应类型是'cors'。

So to fix this, should I change the data to json and then parse the json again to use the data?所以要解决这个问题,我是否应该将数据更改为 json 然后再次解析 json 以使用数据? I think this is very weird.我觉得这很奇怪。 This is because I only want to contain information called 'url' in the response object in the array.这是因为我只想在数组中的响应 object 中包含名为“url”的信息。

We found promise.all to process arrays in parallel, but ordering is not guaranteed.我们发现 promise.all 可以并行处理 arrays,但不能保证订购。 (Is this correct?) (这个对吗?)

No, it isn't correct.不,这是不正确的。 The result array you get on fulfillment of the Promise.all promise is in the same order as the input array, regardless of the order in which the input promises settled.您在满足Promise.all promise 时获得的结果数组与输入数组的顺序相同,无论输入承诺的结算顺序如何。 Here's an example:这是一个例子:

 function delayedValue(ms, value) { return new Promise(resolve => { setTimeout(() => { console.log(`Resolving with ${value}`); resolve(value); }, ms); }); } async function example() { const results = await Promise.all([ delayedValue(100, 1), delayedValue(10, 2), delayedValue(200, 3), ]); console.log(`results: ${results}`); } example();

So you can just use the result directly:所以你可以直接使用结果:

const getAllImagePaths = async urls => {
  try {
    const data = await Promise.all(urls.map(url => fetch(url)));
    return data;
  } catch (err) {
    const { response } = err;

    if (response) alert(MESSAGES.GET_PHOTOS_FAIL);
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM