简体   繁体   中英

How can I make an axios get request synchronous?

I'm relatively new to js and am trying to figure out async-await. I am missing something fundamental. I want to make an HTTP GET that blocks until the response is ready. I built the code below expecting it to print:

main1 false "Some Data" main2

instead it prints:

main1 true undefined main2

How can I resolve this promise inline?

const axios = require('axios');
'use strict'
let URLs= ["http://blah"];
main(process.argv)
function main(argv) {
    console.log('main1');
    const resp = httpgetimpl(URLs[0]);
    console.log(resp instanceof Promise);
    console.log(resp.data);
    console.log('main2');
}
async function httpgetimpl(url) {
    const resp = await axios.get(url);
    return resp;
}

There is no way to make asynchronous operation (like HTTP request) synchronous in JS (there are for sure synchronous API's in node but that's not JS - that's C runtime)

Name of the await keyword is a bit misleading but it doesn't mean "stop the execution of whole program here and do nothing until the operation finishes". It means "return execution flow to my caller (by returning a promise) and when awaited operation is finished, call me back and start executing next line"

It's simply syntactic sugar for Promises...

Your program rewritten using Promises:

function httpgetimpl(url) {
    return axios.get(url).then((resp) =>
      // do something with response if you want
      return resp;
    )    
}

function main(argv) {
    console.log('main1');
    const response = httpgetimpl(URLs[0]).then((resp) =>
    {
      // noop
    })
    // following statements are executed before the axios GET request finishes..
    console.log(response instanceof Promise); // true
    console.log(response.data);  // undefined
    console.log('main2');
}

...hopefully you see why it outputs what you see

If you make your main async and change the call to const resp = await httpgetimpl(URLs[0]); this is the code using Promises:

function httpgetimpl(url) {
    return axios.get(url).then((resp) =>
      // do something with response if you want
      return resp;
    )    
}

function main(argv) {
    console.log('main1');
    return httpgetimpl(URLs[0]).then((resp) =>
    {
      console.log(resp instanceof Promise);
      console.log(resp.data);
      console.log('main2');
    })
}

...which should print the expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM