3

I am new to nodejs and promise based request. I want to fetch the data from a remote server in a loop, and then create a JSON object from all fetched data.

const fetch = require('node-fetch'); const users = []; const ids = await fetch('https://remote-server.com/ids.json'); console.log(ids); // [1,2,3] ids.forEach(id => { var user = await fetch(`https://remote-server.com/user/${id}.json`); users.push(user); }); console.log(users); 

expected output

 [ { name: 'user 1', city: 'abc' }, { name: 'user 2', city: 'pqr' }, { name: 'user 3', city: 'xyz' } ] 
3
  • what is the problem? Commented Jun 5, 2019 at 10:41
  • Console log will always return empty. Let me fiddle a promise function for you, let me warn you though. You can run into very long waiting times doing that. Commented Jun 5, 2019 at 10:42
  • 1
    So. do you want the requests to be launched in parallel or one-by-one? Commented Jun 5, 2019 at 10:42

2 Answers 2

12

So to launch in parallel:

const ids = await fetch('https://remote-server.com/ids.json'); const userPromises = ids.map(id => fetch(`https://remote-server.com/user/${id}.json`)); const users = await Promise.all(userPromises); 

to launch in sequence:

const users = []; const ids = await fetch('https://remote-server.com/ids.json'); for(const id of ids){ const user = await fetch(`https://remote-server.com/user/${id}.json`); users.push(user); } 
Sign up to request clarification or add additional context in comments.

Comments

-2

You forgot to add async in the forEach:

ids.forEach(async (id) => { // your promise is in another function now, so you must specify async to use await var user = await fetch(`https://remote-server.com/user/${id}.json`); users.push(user); }); 

1 Comment

Beware. Array.forEach is not promise-aware, so this represents a "parallel" launching of all requests at once in "fire-and-forget" mode (bad for error-trapping) with no guarantee that the order of the users array will retain the same order as the ids array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.