【发布时间】:2021-07-21 06:02:40
【问题描述】:
我想进行 n 次 api 调用并将所有结果添加到数组中。然后返回数组。
n = 单词数组的长度
它返回一个空结果。我知道这是一个异步函数,但对于我来说,我无法找到解决方案,任何帮助将不胜感激。
app.get('/api/', async (req, res) => {
let wordArray = ["word1", "word2", "word3"]
let resultArray = []
for (let i = 0; i < wordArray.length; i++) {
fetch('apiurl' + new URLSearchParams({
word: wordArray[i],
}))
.then(res => res.json())
.then((responseData) => {
resultArray.push(responseData);
})
.catch(error => console.log(error));
}
console.log(resultArray);
});
【问题讨论】:
-
将promise放入一个数组中,使用
Promise.all()得到所有结果,然后求和。
标签: javascript node.js express asynchronous fetch