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












1















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..










share|improve this question


















  • 3





    JavaScript is asynchronous, the "last part" runs first because the await hasn't returned a result yet.

    – doublesharp
    Jan 3 at 15:50








  • 2





    you'll need to await weather.

    – Daniel A. White
    Jan 3 at 15:50











  • And to await weather() the whole things needs to be inside another async function.

    – doublesharp
    Jan 3 at 15:51











  • add await to weather function

    – Sachin Kadam
    Jan 3 at 15:52











  • As you wrote it yourself, weather() is asynchronous. Meaning non-blocking, meaning console.log("last part") won't wait for it to complete.

    – Jeremy Thille
    Jan 3 at 15:52
















1















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..










share|improve this question


















  • 3





    JavaScript is asynchronous, the "last part" runs first because the await hasn't returned a result yet.

    – doublesharp
    Jan 3 at 15:50








  • 2





    you'll need to await weather.

    – Daniel A. White
    Jan 3 at 15:50











  • And to await weather() the whole things needs to be inside another async function.

    – doublesharp
    Jan 3 at 15:51











  • add await to weather function

    – Sachin Kadam
    Jan 3 at 15:52











  • As you wrote it yourself, weather() is asynchronous. Meaning non-blocking, meaning console.log("last part") won't wait for it to complete.

    – Jeremy Thille
    Jan 3 at 15:52














1












1








1








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..










share|improve this question














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..







javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 3 at 15:47









Abhijeet kumarAbhijeet kumar

128




128








  • 3





    JavaScript is asynchronous, the "last part" runs first because the await hasn't returned a result yet.

    – doublesharp
    Jan 3 at 15:50








  • 2





    you'll need to await weather.

    – Daniel A. White
    Jan 3 at 15:50











  • And to await weather() the whole things needs to be inside another async function.

    – doublesharp
    Jan 3 at 15:51











  • add await to weather function

    – Sachin Kadam
    Jan 3 at 15:52











  • As you wrote it yourself, weather() is asynchronous. Meaning non-blocking, meaning console.log("last part") won't wait for it to complete.

    – Jeremy Thille
    Jan 3 at 15:52














  • 3





    JavaScript is asynchronous, the "last part" runs first because the await hasn't returned a result yet.

    – doublesharp
    Jan 3 at 15:50








  • 2





    you'll need to await weather.

    – Daniel A. White
    Jan 3 at 15:50











  • And to await weather() the whole things needs to be inside another async function.

    – doublesharp
    Jan 3 at 15:51











  • add await to weather function

    – Sachin Kadam
    Jan 3 at 15:52











  • As you wrote it yourself, weather() is asynchronous. Meaning non-blocking, meaning console.log("last part") won't wait for it to complete.

    – Jeremy Thille
    Jan 3 at 15:52








3




3





JavaScript is asynchronous, the "last part" runs first because the await hasn't returned a result yet.

– doublesharp
Jan 3 at 15:50







JavaScript is asynchronous, the "last part" runs first because the await hasn't returned a result yet.

– doublesharp
Jan 3 at 15:50






2




2





you'll need to await weather.

– Daniel A. White
Jan 3 at 15:50





you'll need to await weather.

– Daniel A. White
Jan 3 at 15:50













And to await weather() the whole things needs to be inside another async function.

– doublesharp
Jan 3 at 15:51





And to await weather() the whole things needs to be inside another async function.

– doublesharp
Jan 3 at 15:51













add await to weather function

– Sachin Kadam
Jan 3 at 15:52





add await to weather function

– Sachin Kadam
Jan 3 at 15:52













As you wrote it yourself, weather() is asynchronous. Meaning non-blocking, meaning console.log("last part") won't wait for it to complete.

– Jeremy Thille
Jan 3 at 15:52





As you wrote it yourself, weather() is asynchronous. Meaning non-blocking, meaning console.log("last part") won't wait for it to complete.

– Jeremy Thille
Jan 3 at 15:52












2 Answers
2






active

oldest

votes


















1














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





share|improve this answer

































    0














    // 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))





    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54025577%2fasync-await-not-working-on-making-a-fetch-api-call-in-javascript%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














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





      share|improve this answer






























        1














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





        share|improve this answer




























          1












          1








          1







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





          share|improve this answer















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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 3 at 16:08

























          answered Jan 3 at 15:54









          doublesharpdoublesharp

          19.7k33961




          19.7k33961

























              0














              // 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))





              share|improve this answer




























                0














                // 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))





                share|improve this answer


























                  0












                  0








                  0







                  // 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))





                  share|improve this answer













                  // 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))






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 3 at 15:53









                  vinoth svinoth s

                  795




                  795






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54025577%2fasync-await-not-working-on-making-a-fetch-api-call-in-javascript%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas