// Make a request for user.json fetch('/article/promise-chaining/user.json') // Load it as json .then(response => response.json()) // Make a request to github .then(user => fetch(`https://api.github.com/users/${user.name}`)) // Load the response as json .then(response => response.json()) // Show the avatar image (githubUser.avatar_url) for 3 seconds (maybe animate it) .then(githubUser => { let img = document.createElement('img'); img.src = githubUser.avatar_url; img.className = "promise-avatar-example"; document.body.append(img);
let urls = [ 'https://api.github.com/users/iliakan', 'https://api.github.com/users/remy', 'https://api.github.com/users/jeresig' ];
// map every url to the promise fetch(github url) let requests = urls.map(url => fetch(url));
// Promise.all waits until all jobs are resolved let names = ['iliakan', 'remy', 'jeresig'];
let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));
Promise.all(requests) .then(responses => { // all responses are ready, we can show HTTP status codes for(let response of responses) { alert(`${response.url}: ${response.status}`); // shows 200 for every url }
return responses; }) // map array of responses into array of response.json() to read their content .then(responses =>Promise.all(responses.map(r => r.json()))) // all JSON answers are parsed: "users" is the array of them .then(users => users.forEach(user => alert(user.name)));