简体   繁体   English

在 foreach 循环中进行 api 调用并将结果推送到另一个数组中

[英]make an api call in foreach loop and push the result in another array

I am trying to make an api call in a for each loop.我正在尝试在每个循环中进行 api 调用。 When I make an api call, the function returns the Promise.当我进行 api 调用时,该函数返回 Promise。 I want use that return response and check if the promise is resolved (then do something) and if rejected (then do something).我想使用该返回响应并检查承诺是否已解决(然后做某事)以及是否被拒绝(然后做某事)。 But, everytime in the foreach loop, first the api makes both the calls and then goes to the then() part.但是,每次在 foreach 循环中,api 首先进行两个调用,然后转到 then() 部分。 What I want is in foreach loop, make an api call -> check if resolved or rejected -> do something -> make an api call -> check if resolved or rejected -> do something and so on.我想要的是在 foreach 循环中,进行 api 调用 -> 检查是否已解决或被拒绝 -> 做某事 -> 进行 api 调用 -> 检查是否已解决或被拒绝 -> 做某事等等。

//cannot change the below implementation. //不能改变下面的实现。 I need to use this already created function我需要使用这个已经创建的函数

    const callApiFunction = options => {
      const callback = (resolve, reject) => {
      something.call(options, resolve, reject)
    };
      return new Promise(callback);         
     }

//First attempt //第一次尝试

const a =[];
const b =[];
list.forEach(listelement => {
    callApiFunction(options)
     .then(() => {
         a.push(listelement);
       })
     .catch(() => {
        b.push(listelement);
     });
});

//Second attempt //第二次尝试

    const a =[];
    const b =[];
   list.forEach(listelement => {
    let promise = new Promise((resolve, reject) => {
      callApiFunction(options);
      resolve(listelement);
      reject(listelement);
    });
    promise.then((listelement) => {
      a.push(listelement);
    })
    .catch((listelement) => {
      b.push(listelement);
    });
  });

What happens in my second code block is, callApiFunction is first executed twice if list.length = 2 and then, then is executed twice.在我的第二个代码块中发生的情况是,如果 list.length = 2,则 callApiFunction 首先执行两次, then执行两次。 I want the callApiFunction is executed and list[0] -> then or catch executes accordingly callApiFunction is executed and list[1] -> then or catch executes accordingly我希望 callApiFunction 被执行并且 list[0] -> then or catch 相应地执行 callApiFunction 被执行并且 list[1] -> then or catch 相应地执行

Does this variant with for-of loop and await work for you?这个带有for-of循环和await变体对你await吗?

'use strict';

async function separate(list) {
  const a = [];
  const b = [];

  for (const listelement of list) {
    try {
      await callApiFunction(options);
      a.push(listelement);
    } catch (err) {
      b.push(listelement);
    }
  }

  return [a, b];
}

separate([1, 2, 3]).then(([good, bad]) => {
  console.log(`Success:\n${good.join('\n')}\n\nErrors:\n${bad.join('\n')}\n`);
});

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

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