0

I understand that the following code, will output resolved. My question is how is this useful, and when could async/await be useful when building real world application in react, node, etc ?

function foo() {

   const resolveAfter2Seconds = () => {
    return new Promise(resolve => {
        setTimeout(() => {
          resolve('resolved');
        }, 2000);
      });
   } 

   async function asyncCall(){
    console.log('calling');
    var result = await resolveAfter2Seconds();
    console.log(result);

   }

   return asyncCall;



  }

const myFoo = foo()
myFoo();
randal
  • 1,272
  • 3
  • 23
  • 48
  • 5
    It's useful whenever you're writing code that uses asynchronous functions, which are extremely common in JavaScript. – Barmar Jan 26 '19 at 02:06
  • 1
    For instance, it can be used to write code that makes AJAX requests and uses the result in a more natural way, without having to write a callback function. – Barmar Jan 26 '19 at 02:08
  • 1
    It removes callback hell by giving you the option to write asynchronous code in a seemingly synchronous manner. – Andrew Li Jan 26 '19 at 02:10
  • Async await it's just syntactic sugar over promises resolve reject. Makes the code easier to understand and less cluttered. – shmit Jan 26 '19 at 02:14
  • 1
    If your real question is: "When should I use asynchronous programming in JS", (which is not a fit for SO's QA and too broad as well) then I'd say that node apps use to have async calls to AJAX, UI events in React, and generally anything that you don't want hanging up app for. – Andre Figueiredo Jan 26 '19 at 02:38

1 Answers1

2

The Network, Files, and Frequent Promises

I believe that the most common issues you'll run into that will make you want to switch your current function to async mode usually have to do with: network requests, operating on files, and the frequent use and/or nesting of promises.

Network Requests

When I write network requests I always use the async/await await combo. For me, it makes my code much more linear and readable. I also don't have to worry about returning the promise from fetch (or axios) when I'm done.

async function getPins(user, filterValue) {
  const pins = await axios.get(...);
  if (filterValue) {
    return pins.filter(pin => pin.title.includes(filterValue));
  }
  return pins;
}

Files

async function handleFile(data, isEncrypted, isGzipped) {
  if (isEncrypted) {
    data = await decrypt(data, secret);
  }
  if (isGzipped) {
    data = await ungzip(data);
  }
  return data;
}

Frequent Promises

async function init() {
  const activeBoard = await getActiveBoard();
  const boardMembers = await getBoardMembersFrom(activeBoard);
  const allTasks = [];

  for await (const tasks of boardMembers.map(getTasks)) {
    allTasks.push(task);
    this.setState({ tasks: [...allTasks] });
  }
}

Note: you can use async/await with Promises. There's no need to limit yourself to one or the other.

const test = async props => {
  const data = await fetch('...').then(res => res.json());
  console.log(data) /* do what you want with the data now */
}
Andria
  • 4,712
  • 2
  • 22
  • 38