I'm trying to conceptually understand how ES6 Generators can make async code more streamlined. Here's a contrived example:
- I have a function called getGitHubUser which takes a username and returns a Promise which ultimately resolves to the github user's info.
- I have an array of usernames.
- I'd like to call getGitHubUser with the first username and when that Promise resolves, I want to call getGitHubUser with the next username, and continue this until I've iterated through all the usernames.
I have a working implementation but I'm more curious on how I can leverage generators to make this better.
var getGitHubUser = (user) => {
// using jQuery's $.get
return Promise.resolve($.get("https://api.github.com/users/" + user));
};
var usernames = ["fay-jai", "jyek", "Maestro501", "jaclyntsui"];
getGitHubUser(usernames[0])
.then((result) => {
console.log(result); // fay-jai
return getGitHubUser(usernames[1]);
})
.then((result) => {
console.log(result); // jyek
return getGitHubUser(usernames[2]);
})
.then((result) => {
console.log(result); // Maestro501
return getGitHubUser(usernames[3]);
})
.then((result) => {
console.log(result); // jaclyntsui
});