Abhijeet kumar
Abhijeet kumar

Reputation: 61

Async /await not working on making a fetch API call in javascript

I am making a fetch API call from my js file ,I have a doubt that when i am using Async/await still the code is executing in asynchronous manner.

I have also tried await at differnt place but its doesn't work.

 let info
 async function weather(){
 // API call
 let data=await fetch('http://api.openweathermap.org/data/2.5/weather?'+'&lat=20&lon=44'+'&units=metric'+'&APPID='+WEATHER_KEY)
  console.log("inside API")
  const res= await data.json();
  console.log(res)
 }
weather()
console.log("last part")

OUTPUT:

last part

inside API

"VALUE OF RES"

WHAT I EXPECT:

inside API

"VALUE OF RES"

last part

Any help will be highly appreciated..

Upvotes: 1

Views: 6193

Answers (3)

Juan Carlos Serrano
Juan Carlos Serrano

Reputation: 103

A solution in a script that run in node environment:

(async function () {

  // API call
  const data = await fetch('http://api.openweathermap.org/data/2.5/weather?'+'&lat=20&lon=44'+'&units=metric'+'&APPID='+WEATHER_KEY)
  console.log("inside API")

  const res = await data.json();
  console.log(res)

  console.log("last part")
})()

The messages will are in expected order.

Upvotes: 0

doublesharp
doublesharp

Reputation: 27609

The easiest way is to wrap it all in another async function so that you can await weather().

// this function fetches the weather then logs the result
async function weather() {
  // API call
  let data = await fetch('http://api.openweathermap.org/data/2.5/weather?'+'&lat=20&lon=44'+'&units=metric'+'&APPID='+WEATHER_KEY);
  console.log('inside API');
  const res = await data.json();
  console.log(res);
}

// this async function awaits for weather() to return
async function run() {
  await weather();
  console.log('last part');
}

// this runs first
run();

Upvotes: 1

vinoth s
vinoth s

Reputation: 198

// async function
async function fetchAsync () {
  // await response of fetch call
  let response = await fetch('http://api.openweathermap.org/data/2.5/weather?'+'&lat=20&lon=44'+'&units=metric'+'&APPID='+WEATHER_KEY);
  // only proceed once promise is resolved
  let data = await response.json();
  // only proceed once second promise is resolved
  return data;
}

// trigger async function
// log response or catch error of fetch promise
fetchAsync()
    .then(data => console.log(data))
    .catch(err => console.log(err))

Upvotes: 0

Related Questions