admin管理员组

文章数量:1290186

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('.json');
console.log(ids);
// [1,2,3]

ids.forEach(id => {
    var user = await fetch(`/${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'
        }
    ]

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./ids.json');
console.log(ids);
// [1,2,3]

ids.forEach(id => {
    var user = await fetch(`https://remote-server./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'
        }
    ]
Share Improve this question asked Jun 5, 2019 at 10:39 JitJit 411 silver badge3 bronze badges 3
  • what is the problem? – brk 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. – jPO Commented Jun 5, 2019 at 10:42
  • 1 So. do you want the requests to be launched in parallel or one-by-one? – spender Commented Jun 5, 2019 at 10:42
Add a ment  | 

2 Answers 2

Reset to default 12

So to launch in parallel:

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

to launch in sequence:

const users = [];
const ids = await fetch('https://remote-server./ids.json');
for(const id of ids){
    const user = await fetch(`https://remote-server./user/${id}.json`);
    users.push(user);
}

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./user/${id}.json`);
    users.push(user);
});

本文标签: javascriptHow to run fetch() in a loopStack Overflow