所以我有一些这样的代码
const getAPIData = (symbol, callback) => {
var options = {
url: "https://api.binance.com/api/v3/ticker/price",
method: "GET",
qs: {
symbol
},
};
request(options, (err, res, body) => {
body = JSON.parse(body);
callback(body);
});
};
var isValid = 0;
getAPIData(symbol, (body) => {
console.log(body);
if (body.symbol) {
console.log("yes");
isValid = 1;
} else {
console.log("no");
}
});
执行此回调后,无论结果如何,“ isValid”变量仍保持为0。尽管控制台会以“是”和“否”两种方式登录。当我调试程序时,isValid变量仍然保持为0。
console.log函数如何工作并且不将isValid设置为1?就像只是跳过那一行,或者我不确定。请帮帮我!
这是异步调用的工作方式。
var isValid = 0;
getAPIData(symbol, (body) => {
console.log(body);
if (body.symbol) {
console.log("yes");
isValid = 1;
console.log(isValid); // 1
} else {
console.log("no");
}
});
console.log(isValid); // 0
// when the JS engine gets here, isValid will still be 0
// since getAPIData is asynchronous and it's still in progress at this point
// also, you cannot use any results of getAPIData here