一次打印递归所有节点获取操作信息



我有以下javascript代码,其中我正在为数组中显示的用户获取github配置文件信息。

const fetch = require('node-fetch');                                                
const users = ["nayabbashasayed", "AmruthPillai"]                                   
const getGithubProfiles = (users) => {
let userGitProfiles = [];
users.forEach(user => {                                                         
const url = 'https://api.github.com/users/' + user;                         
fetch(url).then(res => res.json()).then(body => {                           
userGitProfiles.push(body);                                             
});                                                                         
});
console.log(userGitProfiles);
}                                                                                   
getGithubProfiles(users);

我正在使用节点来运行代码。

由于异步性质,代码行console.log(userGitProfiles);打印首先导致输出[]然后发生提取操作。

如何等待所有操作完成,然后一次打印所有信息?

你可以使用 Promise.all 来获取所有用户配置文件并获取单个数组

const fetch = require('node-fetch');
const users = ["nayabbashasayed", "AmruthPillai"]
const getGithubProfiles = (users) => {
let userGitProfiles = [];
let Q = []
users.forEach(user => {
const url = 'https://api.github.com/users/' + user;
Q.push(fetch(url).then(res => res.json()))
});
return Promise.all(Q)
}
getGithubProfiles(users).then(
userProfiles => console.log(userProfiles)
);

最新更新