0

I want to make n amount of api calls and add the all the results to an array. Then return the array.

n = length of word array

It is returning an empty result. I know it's an async function but for the life of me I can't figure out a solution, any help would be appreciated.

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);
});
1
  • 1
    Put the promises in an array, use Promise.all() to get all the results, then sum that. Commented Apr 27, 2021 at 21:18

1 Answer 1

1

You are using async call, then you console.log resultArray, after that async call is executed. You should wrap everything in 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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.