Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

return response from async call

// Using 'superagent' which will return a promise.
var superagent = require('superagent')

// This is isn't declared as `async` because it already returns a promise
function delay() {
  // `delay` returns a promise
  return new Promise(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);
  });
}

async function getAllBooks() {
  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)
    await delay();
    // GET information about each book
    return await 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
    return null;
  }
}

// Start an IIFE to use `await` at the top level
(async function(){
  let books = await getAllBooks();
  console.log(books);
})();
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript entries() method 
Javascript :: how to craete an array in js 
Javascript :: GET FORM VALUE 
Javascript :: get all database react native 
Javascript :: Get title assert 
Javascript :: how to decode jwt token in angular 
Javascript :: javascript regular expression 
Javascript :: javascript factory functions 
Javascript :: js indexof string 
Javascript :: is loop backward 
Javascript :: js arrow anonymous function 
Javascript :: javascript call stacks 
Javascript :: js regexp match 
Javascript :: js get location params 
Javascript :: has class in jquery 
Javascript :: how to lose overflow in js without hidden 
Javascript :: how to get current time using moment 
Javascript :: A better way to concatenate arrays 
Javascript :: css javascript 
Javascript :: a full express function 
Javascript :: for loop js Alternatives 
Javascript :: console log on html 
Javascript :: Progress bar loader angular 
Javascript :: js print objects 
Javascript :: react moment calendar times 
Javascript :: scirpt tag react 
Javascript :: js some 
Javascript :: location maps react native 
Javascript :: address validation in javascript 
Javascript :: clean-webpack-plugin clearing dist folder 
ADD CONTENT
Topic
Content
Source link
Name
6+7 =