[英]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.