【问题标题】:nodejs array returning empty. async questionnodejs 数组返回空。异步问题
【发布时间】: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


【解决方案1】:

您正在使用异步调用,然后在执行该异步调用之后使用 console.log resultArray。您应该将所有内容都包装在 promise.all 中

const wordArray = ["word1", "word2", "word3"]

let resultArray = [];

let actions = [];
for (let i = 0; i < wordArray.length; i++) {
  const action = fetch('apiurl' + new URLSearchParams({
    word: wordArray[i],
  }))
    .then(res => res.json())
    .then((responseData) => {
        resultArray.push(responseData);
    })
    .catch(error => { console.log(error) });
  
  actions.push(action);
}

Promise.all(actions).then(() => {
  console.log(resultArray);
});

【讨论】:

  • 完美运行。谢谢你的解释! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
相关资源
最近更新 更多