randal
randal

Reputation: 1362

When could async/await in javascript be useful?

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();

Upvotes: 0

Views: 82

Answers (1)

Andria
Andria

Reputation: 5075

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 */
}

Upvotes: 2

Related Questions