简体   繁体   English

如何在 Node.js 中的异步 function 之外使用变量?

[英]How can I use a variable outside an async function in Node.js?

I am trying to use the variable bida elsewhere in my code.我正在尝试在我的代码中的其他地方使用变量bida For example, when I try to create the variable mida .例如,当我尝试创建变量mida时。 Is there a way to do that without nesting everything inside the getFX() function?有没有办法做到这一点,而无需将所有内容都嵌套在getFX() function 中? I understand it's an async function issue but how can I get around it?我知道这是一个异步 function 问题,但我该如何解决?

const fetch = require("node-fetch");

async function getFX() {

let bida;

  try {

    var req = await fetch('https://economia.awesomeapi.com.br/all/USD-BRL');
    var response = await req.json()


   bida = await response.USD.bid;
   aska = await response.USD.ask;

    console.log(bida, aska)

  } catch (e) {
    // handle error
    console.error(e)
  }
}

getFX()

var mida = bida + 1;

console.log (mida);

you should initialize the bida variable outside of the getFX() function to be able to access it elsewhere in that file, and also set the value of mira variable only when getFX resolves using.then() to be able to use the value of bida because getFX is an async function.您应该在 getFX() function 之外初始化 bida 变量,以便能够在该文件的其他位置访问它,并且仅在 getFX 解析 using.then() 时才设置 mira 变量的值,以便能够使用 bida 的值因为 getFX 是异步 function。 Here is how I did it:我是这样做的:

const fetch = require("node-fetch");

let bida;

async function getFX() {


    try {

       var req = await fetch('https://economia.awesomeapi.com.br/all/USD-BRL');
       var response = await req.json()


       bida = await response.USD.bid;
       aska = await response.USD.ask;

       console.log(bida, aska)

    } catch (e) {
        // handle error
        console.error(e)
    }
}


getFX().then(() => {
    var mida = bida + 1;
    console.log (mida);
})

Hope it helps !希望能帮助到你 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用异步函数作为node.js中的回调吗? - Can I use a async function as a callback in node.js? 如何管理Node.js异步变量作用域? - How can I manage Node.js async variable scope? 如何在 Node.JS 代码中的套接字事件之外使用 scope 上的 let 变量? - How can I use the let variable on scope outside the socket event, in the Node.JS code? 如何在 Node.js 中的 function 外部访问 await function 变量 - How to access await function variable outside function in Node.js 我想在node.js外部使用mysql函数的变量 - I want use mysql function's variable to the outside in node.js 使用异步的Node.js-如何正确地将async.forEachLimit与fs.readFile一起使用? - Node.js using async - How can I properly use async.forEachLimit with fs.readFile? Node.JS变量外函数 - Node.JS variable outside function 如何在node.js中的异步函数内使用for循环? - How to use for loop inside an async function in node.js? node.js koa无法通过异步函数将值发送到客户端,但是在外部 - node.js koa can't sent value to the client in a async function,but outside 我无法在其 function 之外识别任何变量(在本例中为“app.get”(node.js)) - I can't get any variable to be recognized outside of its function (in this case “app.get” (node.js))
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM