database - Get that user's best friend - Get that best friend's profile picture - Add a mustache to everybody in the picture - Show the transformed picture on the page
Promise(function (resolve, reject) { // ... Do some asynchronous things // Eventually call resolve or reject }); Promise.resolve({ myResult: 123 }); Promise.reject(new Error("BAD THINGS"));
var nextAddition = (yield accumulator); accumulator += nextAddition; } } var sum = sumUpNumbers(); sum.next(); // Need an initial next(), to run to first yield. sum.next(1); // { value: 1, done: false } sum.next(5); // { value: 6, done: false }
function step(input) { var result = generator.next(input); var value = Promise.resolve(result.value); if (result.done) return value; else return value.then(step); } return step(); } // (Error handling omitted)
await loadUserFromDatabase(userId); var friend = await getBestFriend(user); var photo = await friend.getBestPhoto(); var betterPhoto = await addMustache(photo); return showPhotoToUser(user, betterPhoto); } mustachify(userId).catch(function (error) { // You can still use catch() - it's promises under the hood });
user = await loadUserFromDatabase(userId); var friend = await getBestFriend(user); var photo = await friend.getBestPhoto(); var betterPhoto = await addMustache(photo); return showPhotoToUser(user, betterPhoto); } catch (error) { // Try/catch now works with promises & async too } } mustachify(userId);
var friendData = friendIds.map(function (friendId) { // This code isn't in an async function, // so this is a syntax error. return (await getUserData(friendId)); }); return friendData.map(function (friend) { return friend.name; }); }