Search code examples
javascriptasync-awaitjavascript-objects

What is the difference between an async function, a promise and an observable?


Can anyone explain when to use async and await?

I want to write a method in angular application class, which will wait for the response of API call. Is it good to use Promise instead?

If both of them are asynchronous then when to use Promise instead of an async function?

What are observables? How they differ from Promises?


Solution

  • There are two branches in the question.

    1. What are async functions, how they are different from promise constructor and what are observables.
    2. When to use Observables and When to use Promises/Async functions.

    I know this can be long enough to fill a wiki page, but from a pragmatic point of view it can be answered and may be useful to actually create practical informative resources.

    About the first branch.

    Promise: is an object that wraps a value, you interact with the value through the then method of the promise. You can learn more about Promises itself in javascript in https://promisesaplus.com/. This is specially useful for asynchronous operations, because you can decouple what the operation is and what you're going to do with the result of such operation

    Aync functions: an async function is a function that is decorated to be asynchronous through the async sentence. Within this function you can use await to unwrap values from promises, and the value you return is automatically wrapped by a Promise (so you don't have to explicitly return a promise). These are specially useful for asynchronous operations because you can decouple the controls of a set of asynchronous operations and the control flow of the combination of those operations. You can learn more about async functions in https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Sentencias/funcion_asincrona.

    Observables: is an object that wraps a value that changes over time, normally this change is pictured as a sequence of values. You interact with the values using the subscribe method. You could learn more by using marble http://rxmarbles.com/ and the docs. I would also recommend this article https://gist.github.com/staltz/868e7e9bc2a7b8c1f754

    About the second branch: as always it depends on the situation and the problem.

    You could use a Promise when you request a value from a REST API or an Async Reader, because it is a single value and a Promise is easy to work with, it has a low learning curve.

    const getDataFromFile = (fileName) => new Promise(resolve => {
      readFile(fileName, content => resolve(content);
    });
    

    You could use an Async function to do calculations and transformations from a value you request from various a REST APIs or simply functions that return promises

    async function concatFiles(fileName1, fileName2) {
      const content1 = await getDataFromFile(fileName1);
      const content2 = await getDataFromFile(fileName2);
      return content1 + content2; // or just `$`
    }
    

    You could use observables for values that will change over time, you can address these changes to events and can address the values to states of something. Like a select it will trigger a change and will wrap a value

    Observable.fromEvent(selectElement, 'change').subscribe(e => console.log(e))
    

    About the second branch: you use what fits on the problem

    Now, Angular proposes an architecture trait, and maybe this architecture (or architecture in other frameworks) asks you to use observables, and you have to handle it. But if you can choose, just use what fits the problem better by simplifying it in reasonable parts.

    Extra branch of the question or how does all those structures come from and why?

    There are plenty of reasons of why promises, async functions and observables have been created, and all of this is related to reactive programming, asynchrony, non blocking design of programs among others.

    Hope it helps.