- Loads the post titles for a given user ID. * @param userId is the ID of the user whose posts you want to load * @returns a Promise that resolves to an array of post titles */ function getPostTitles(userId) { return getUser(userId) // Callback is called with the loaded user object .then(user ⇒ { console.log(`Getting posts for ${user.name}`); // This Promise is also returned from .then return getPosts(user); }) // Calling then on the getPosts' Promise .then(posts ⇒ { // Returns another Promise that will resolve to an array of post titles return posts.map(post ⇒ post.title); }) // Called if either getUser or getPosts are rejected .catch(error ⇒ { console.error('Error loading data:', error); }); }
- Sends a GET request to the specified URL. Returns a Promise that will resolve to * the JSON body parsed as an object, or will reject if there is an error or the * response is not valid JSON. * * @param url The URL to request * @returns a Promise that resolves to the response body */ function loadJSON(url) { // Create a new Promise object, performing the async work inside the // constructor function. return new Promise((resolve, reject) ⇒ { const request = new XMLHttpRequest(); // If the request is successful, parse the JSON response and // resolve the Promise with the resulting object. request.addEventListener('load', event ⇒ { // Wrap the JSON.parse call in a try/catch block just in case // the response body is not valid JSON. try { resolve(JSON.parse(event.target.responseText