首页 > 解决方案 > (JS, Promise) 如何等待来自多个 map 函数的 Promise

问题描述

我有三个数组:

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只是有未解决的承诺。

我做错了什么?

标签: javascriptpromise

解决方案


我会这样做:


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}`)
}());

推荐阅读