Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript nodejs数组返回空。异步问题_Javascript_Node.js_Express_Asynchronous_Fetch - Fatal编程技术网

Javascript nodejs数组返回空。异步问题

Javascript nodejs数组返回空。异步问题,javascript,node.js,express,asynchronous,fetch,Javascript,Node.js,Express,Asynchronous,Fetch,我想进行n次api调用,并将所有结果添加到一个数组中。然后返回数组 n=单词数组的长度 它正在返回一个空结果。我知道这是一个异步函数,但就我的一生而言,我无法找到解决方案,任何帮助都将不胜感激 app.get('/api/', async (req, res) => { let wordArray = ["word1", "word2", "word3"] let resultArray = [] fo

我想进行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);
});
app.get('/api/',异步(req,res)=>{
让wordArray=[“word1”、“word2”、“word3”]
让resultArray=[]
for(设i=0;ires.json())
.然后((响应数据)=>{
结果推送(响应数据);
})
.catch(错误=>console.log(错误));
}
console.log(resultArray);
});

您使用的是异步调用,然后在执行该异步调用后,使用console.log resultaray。你应该用承诺来包装一切

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);
});
const wordArray=[“word1”、“word2”、“word3”]
设resultArray=[];
让动作=[];
for(设i=0;ires.json())
.然后((响应数据)=>{
结果推送(响应数据);
})
.catch(错误=>{console.log(错误)});
动作。推(动作);
}
承诺。所有(行动)。然后(()=>{
console.log(resultArray);
});

将承诺放在一个数组中,使用
Promise.all()
获得所有结果,然后求和。效果非常好。谢谢你的解释!:)