gpt4 book ai didi

javascript - 如何在循环中运行 fetch()?

转载 作者:行者123 更新时间:2023-12-02 14:49:42 25 4
gpt4 key购买 nike

我是 nodejs 和基于 promise 的请求的新手。我想在循环中从远程服务器获取数据,然后根据所有获取的数据创建一个 JSON 对象。

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);

预期输出

    [
{
name: 'user 1',
city: 'abc'
},
{
name: 'user 2',
city: 'pqr'
},
{
name: 'user 3',
city: 'xyz'
}
]

最佳答案

因此并行启动:

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);

按顺序启动:

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);
}

关于javascript - 如何在循环中运行 fetch()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56458863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com