我有三个数组:
File/Directory *next
我必须使用所有可能的组合发送多个请求,并等待所有响应得到解决,然后再继续。 所以我尝试这样做
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();
}
仅具有未解决的承诺。
我做错了什么?
答案 0 :(得分: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}`)
}());
答案 1 :(得分:1)
用.map
解决问题的方法不起作用,因为嵌套的map函数返回嵌套数组,并且Promise.all
期望一个promise数组作为条目而不是数组本身。
最好的方法可能是使用嵌套的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);
};
答案 2 :(得分: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})