DEV Community

CBAD
CBAD

Posted on

Asynchronous Javascript

What is Asynchronous Javascript?

  • Javascript is a single-threaded programming language. This means that processes run one at a time. Asynchronous Javascript allows us to schedule processes that don't block the main thread.

Our options writing asynchronous code

Callbacks

  • In order to use callbacks to do asynchronous work, we simply provide a callback to the function that is doing the asynchronous work. When the work resolves, we will call the passed in callback function with the result of asynchronous work.

Promises

  • A promise is an object that can produce a value sometime in the future. Instead of providing a call back to our function that does asynchronous work. We can instead return a new Promise. Promises are initialized with a callback function that takes two arguments, "resolve" and "reject". Inside this callback function is where we kickoff our asynchronous work. When we want to return the result we simply call resolve and pass it the results. Otherwise we call reject and pass it the error. When a function returns a promise we are able to consume a promise by attaching then() statements to the result. This allows us to either see the resolve or rejection returned by the promise.

Async / Await

  • The only difference between the last method and using async and await is how we consume our promises. Instead chaining then callbacks we can wrap our consumption in a function decorated with the "async" keyword. Inside this function we can use a try and catch block. and inside the try we can await the results from out async functions. If at any point they fail the error will be handled in the catch block, otherwise we are free to work with the data in our try block.

Top comments (0)