Synchronous and Asynchronous Code

From Logic Wiki
Jump to: navigation, search


Patterns for Dealing with Async Code

Callbacks

function here is the callback function. We pass it to getUser and when it's completed this callback is triggered

getUser(1, function(user) {
    console.log('User', user);
});

Callback function can be in any name but then both parameter and function call must be renamed simultaneously.

function getUser(id, callback) {
   setTimeout(()=> {
       callback({ id:id, username:'test'});
   }, 2000);

Promises

A promise is an object that holds the eventual result of an asynchronous operation

3 states of a promise object

  • Pending
  • Fullfilled (resolved)
  • Rejected (error)
const p = new Promise((resolve, reject) => {
  resolve(1);
//  reject(new Error('message'));
});
   p
     .then(result => console.log('Result : ' + result);
     .catch(err=> console.log('Error : ' + err.message));

Parallel Promises

const p1 = new Promise((resolve) = { 
  setTimeout()=> {
      console.log("Async operation 1");
      resolve(1);
  }, 2000);
});

const p2 = new Promise((resolve) = { 
  setTimeout()=> {
      console.log("Async operation 2");
      resolve(2);
  }, 2000);
});

Promise.all([p1, p2])
  .then(result => console.log(result));
  .catch(err => console.log('Error', err.message));

if any one of the promises rejected all rejected

Promise.race(... if we want to return immediately only one of them resolved

Async/await

async function displayAll(){
const user = await getUser(1);
const repos = await getRepositories(user.id);
}
  displayAll()