Asynchronous

js

Agenda:

  • Promise
  • Event loop
  • Async/await
  • Fetch API
  • HW

Callback Hell

getImage('/image.png', (image, err) => {
  if(err) throw new Error(err)
  compressImage(image, (compressedImage, err) => {
    if(err) throw new Error(err)
    applyFilter(compressedImage, (filteredImage, err) => {
      if(err) throw new Error(err)
      saveImage(filteredImage, (result, err) => {
        if(err) throw new Error(err)
        console.log('Successfully saved image')
      })
    })
  })
})

Promise

The value of promise status:

 

fulfilled: The promise has been resolved. Everything went fine, no errors occurred within the promise.

❌ rejected: The promise has been rejected. Argh, something went wrong...

⏳ pending: The promise has neither resolved nor rejected (yet), the promise is still pending.

 

.then(): Gets called after a promise resolved.
.catch(): Gets called after a promise rejected.
.finally(): Always gets called, whether the promise resolved.

getImage('/image.png', (image, err) => {
  if(err) throw new Error(err)
  compressImage(image, (compressedImage, err) => {
    if(err) throw new Error(err)
    applyFilter(compressedImage, (filteredImage, err) => {
      if(err) throw new Error(err)
      saveImage(filteredImage, (result, err) => {
        if(err) throw new Error(err)
        console.log('Successfully saved image')
      })
    })
  })
})

VS

asyncThing1().then(function() {
  return asyncThing2();
}).then(function() {
  return asyncThing3();
}).catch(function(err) {
  return asyncRecovery1();
}).then(function() {
  return asyncThing4();
}, function(err) {
  return asyncRecovery2();
}).catch(function(err) {
  console
    .log("Don't worry about it");
}).then(function() {
  console
    .log("All done!");
})

Example was taken from 

Promise.reslove and Promise.reject

Promise.all and Promise.race

const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two');
});



Promise.all([promise1, promise2]).then((values) => {
  console.log(values);
});
// expected output: ["one", "two"]


Promise.race([promise1, promise2]).then((value) => {
  console.log(value);
  // Both resolve, but promise2 is faster
});
// expected output: "two"

Microtasks and (Macro)tasks

However, within the Event Loop, there are actually two types of queues: the (macro)task queue (or just called the task queue), and the microtask queue. The (macro)task queue is for (macro)tasks and the microtask queue is for microtasks.

(Macro)task
 
Microtask
setTimeout process.nextTick
setInterval Promise callback
setImmediate queueMicrotask

Text

 ⚠️⚠️ ATTENTION ⚠️⚠️

Async/await

Fetch API

Example of POST request:

fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})

Fetch is the next generation of XHR

fetch('/users')
  .then(checkStatus)
  .then(parseJSON)
  .then(function(data) {
   console.log('request succeeded', data)
  }).catch(function(error) {
    console.log('request failed', error)
  })

Response:

function checkStatus(response) {
  if (response.status >= 200 &&
      response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json()
}
async function getUsers() {
  try {
    const res = await fetch('/users');
    checkStatus(res);
    const body = await res.json();
    console.log('request succeeded', body);
  } catch (error) {
    console.log('request failed', error);
  }
}

Streams

response.body is a ReadableStream

How to deals with stream

.json()

.text()

.blob()

.formData()

.arrayBuffer()

 

.clone()

fetch(url).then(function(response) {
  return response.json();
});

CRUD:

C = CREATE   

R = READ 

U = UPDATE 

D = DELETE

 

POST

GET

PUT

DELETE

 

FREE APIs for practice:

  • https://www.mockable.io/
  • https://locationiq.com/
  • https://weatherstack.com/

The END

Asynchronous js

By Aleh Lipski

Asynchronous js

  • 106