1

我有三个数组:

const firstArray = ['a', 'b', 'c']
const secondArray = ['i', 'j', 'k']
const thirdArray = ['x', 'y', 'z']

我必须使用所有可能的组合发送多个请求,并等待所有响应得到解决,然后再继续。所以我试着这样做

const getPromises = () => {
    const promises = firstArray.map(first => {
          return secondArray.map(second => {
            return thirdArray.map(third => {
              return axios.get(`https://someurl.com/${first}/${second}/${third}`)
                                .then(response => response);
            })
          })
        })
      return Promise.all(promises)
    }

我有另一种方法,我试图从这个方法中获取返回值

const getvalues = async () => {
    const someVariable = await getPromises();
}

但它没有成功。变量someVariable只是有未解决的承诺。

我做错了什么?

4

3 回答 3

2

我会这样做:


const getPromises = () => Promise.all(function* () {
    for (let first of firstArray)
        for (let second of secondArray)
            for (let third of thirdArray)
                yield axios.get(`https://someurl.com/${first}/${second}/${third}`)
}());
于 2020-03-14T12:42:13.880 回答
1

解决您的问题的方法.map不起作用,因为嵌套的映射函数正在返回嵌套数组,并Promise.all期望将一组承诺作为条目而不是数组本身。

最好的方法可能是使用嵌套for...of循环:

const firstArray = ['a', 'b', 'c'];
const secondArray = ['i', 'j', 'k'];
const thirdArray = ['x', 'y', 'z'];

const getPromises = () => {
  const promises = [];
  for (let first  of firstArray )
  for (let second of secondArray)
  for (let third  of thirdArray ) {
    promises.push(axios.get(`https://someurl.com/${first}/${second}/${third}`));
  }
  return Promise.all(promises);
};
于 2020-03-14T12:08:39.867 回答
0

这是一个显示您需要的示例:

const a = ['a', 'b', 'c'];
const b = ['i', 'j', 'k'];
const c = ['x', 'y', 'z'];

let promises = [];

a.forEach((i1) => {
  b.forEach((i2) => {
    c.forEach((i3) => {
      let promise = new Promise((res, rej) => {
        setTimeout(function() {
          res([i1, i2, i3])
        }, 250)
      }).then(([j1, j2, j3]) => console.log(j1, j2, j3));
      promises.push(promise);
    })
  })
});

Promise.all(promises).then(() => console.log("finish"));

只需setTimeout用你的替换axios.get(https://someurl.com/${first}/${second}/${third})

于 2020-03-14T12:07:06.927 回答