sinusGob
sinusGob

Reputation: 4313

Why do I need to async/await again in a different function?

I'm confused of why do I need to run the async/await again in another function

Example

async function fetchData() {
   try {
        const result = await axios.get('http://example.com')
        return result

    } catch(err) {
       return err

     }
}


// and in another function I need to async await again 

// if I want to get the value of fetchData() 

// or else it will return pending promise object


function mapData() {
     const data = fetchData()
     console.log(data) // is a Pending Promise    
}

If I want to get the data instead of Promise object

async function mapData() {
     const data = await fetchData() // I still need to await?? 
     console.log(data) // real value
}

I thought that If I already async/await in fetchData function it's already return a value instead of promise, why do I need to async/await again to get the actual data in mapData function?

Upvotes: 1

Views: 83

Answers (2)

Thomas
Thomas

Reputation: 12637

Promises deal with time. They are a wrapper for a value that will be available eventually, BUT NOT YET. And you don't freeze your entire app untill the value is avilable.

async/await is just syntactic sugar over Promises. It lets you write code like

async function myFunction(){
  var id = await asyncMethod1();
  var value = await asyncMethod2(id);
  return syncMethod3(id, value);
}

instead of

function myFunction(){
  return asyncMethod1().then(id => asyncMethod2(id).then(value => syncMethod3(id, value)));
}

but it doesn't change how this thing works underneath.

So although syncMethod3 is sync the returned value still relies on the asyncronously computed values foo and bar. which makes myfunction async.

And every function that calls myFunction needs to wait untill myFunction has computed its value, ... and so on.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

An async function will always return a Promise - a Promise that resolves once the async function reaches its end (after any possible containing awaits). It doesn't magically make asynchronous code synchronous; any consumers of an async function will have to deal with its asynchronity as well.

It also usually makes more sense to handle errors in the consumer. Here, it doesn't look like you're doing anything special with the error in fetchData, so you can return the Promise immediately, without having to await it in the downstream function:

function fetchData() {
   return axios.get('http://example.com');
}
async function mapData() {
     try {
       const data = await fetchData()
       console.log(data)
     } catch(e) {
       console.log('Something went wrong...');
       // handle failure of fetchData
     }
}

Upvotes: 4

Related Questions