回调函数有问题
Having an issue with callback function
所以我有一些这样的代码
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。尽管控制台被记录为 yes 和 no 两者。当我调试程序时,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
所以我有一些这样的代码
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。尽管控制台被记录为 yes 和 no 两者。当我调试程序时,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