// Using 'superagent' which will return a promise. var superagent = require('superagent');
// This is isn't declared as `async` because it already returns a promise functiondelay() { // `delay` returns a promise returnnewPromise(function(resolve, reject) { // Only `delay` is able to resolve or reject the promise setTimeout(function() { resolve(42); // After 3 seconds, resolve the promise with value 42 }, 3000); }); }
asyncfunctiongetAllBooks() { try { // GET a list of book IDs of the current user var bookIDs = await superagent.get('/user/books'); // wait for 3 seconds (just for the sake of this example) awaitdelay(); // GET information about each book return superagent.get('/books/ids='+JSON.stringify(bookIDs)); } catch(error) { // If any of the awaited promises was rejected, this catch block // would catch the rejection reason returnnull; } }
// Start an IIFE to use `await` at the top level (asyncfunction(){ let books = awaitgetAllBooks(); console.log(books); })();
functiondelay() { // `delay` returns a promise returnnewPromise(function(resolve, reject) { // Only `delay` is able to resolve or reject the promise setTimeout(function() { resolve(42); // After 3 seconds, resolve the promise with value 42 }, 3000); }); }
delay() .then(function(v) { // `delay` returns a promise console.log(v); // Log the value once it is resolved }) .catch(function(v) { // Or do something else if it is rejected // (it would not happen in this example, since `reject` is not called). });