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
2 Answers
Reset to default 12So 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
版权声明:本文标题:javascript - How to run fetch() in a loop? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741471726a2380646.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论