【问题标题】:How can I make an axios get request synchronous?如何使 axios 获取请求同步?
【发布时间】:2021-01-25 11:53:04
【问题描述】:

我对 js 比较陌生,正在尝试找出 async-await。我缺少一些基本的东西。 我想制作一个阻塞的 HTTP GET,直到响应准备好。我构建了下面的代码,期望它打印出来:

main1 错误的 “一些数据” 主要2

而是打印:

main1 真的 不明确的 主要2

我怎样才能内联解决这个承诺?

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;
}

【问题讨论】:

  • await 不会使任何东西同步。它使编写异步代码更容易。也就是说,只需将mainasync function 以及await 设为您得到的承诺。
  • 如果你在 httpgetimpl() 方法中 console.log(resp.data); 你会得到什么?
  • 'use strict' 应该是第一个生效的语句(在文件或函数中)
  • @Ricardo Sanchez console.log(resp.data); => 打印响应,但在 main2 之后
  • 试试return await axios.get(url);

标签: javascript async-await axios


【解决方案1】:

在 JS 中无法使异步操作(如 HTTP 请求)同步(节点中肯定有同步 API,但那不是 JS - 那是 C 运行时)

await 关键字的名称有点误导,但这并不意味着“在此处停止整个程序的执行,并且在操作完成之前什么都不做”。这意味着“将执行流程返回给我的调用者(通过返回一个承诺),当等待的操作完成时,给我回电并开始执行下一行”

它只是 Promises 的语法糖......

使用 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');
}

...希望你明白为什么它会输出你所看到的

如果您拨打main async 并将调用更改为const resp = await httpgetimpl(URLs[0]);,这是使用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');
    })
}

...应该打印预期的

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2021-05-11
    • 2021-12-19
    • 2020-02-10
    • 2012-02-14
    • 2020-05-31
    相关资源
    最近更新 更多