我正在尝试在 if 条件下使用 Promises。我面临的问题是即使 if 语句为假,它下面的代码仍然执行。我该如何修复这个错误?
此处为示例,但链接中有完整代码:https://jsbin.com/qezimeyopo/edit?js
//MAIN TRAILING STOPLOSS
async function binanceTrailingSLOrder(symbol, orderId, quantity, oldPrice, percentage, active) {
const clean_trade = client.ws.trades([symbol], async trade => { //run websocket
var livePrice = parseFloat(binance_symbols[symbol]["close"]); //set new price to live price
console.log("1) order ID: " + orderId + " active: " + active);
if (active == true) {
try {
const orderStatus = await binanceCheckOrderStatus(symbol, orderId);
console.log("2) order ID: " + orderId + " active: " + active + ", new SL: " + (oldPrice * ((100 + percentage) / 100)));
switch (orderStatus.status) {
case "NEW":
case "PENDING":
console.log("Still running ...");
if (livePrice >= (oldPrice * ((100 + percentage) / 100)) && active == true) {
active = false;
const cancelOrder = await binanceCancelOrder(symbol, orderId);
if (cancelOrder) {
console.log("Old SL cancelled");
var newSL = livePrice * ((100 - percentage) / 100);
newSL = binanceNormalizePrice(symbol, newSL);
try {
const newStopLoss = await binanceStopOrder(symbol, 'SELL', quantity, newSL, newSL);
if (newStopLoss) {
orderId = newStopLoss.orderId;
quantity = newStopLoss.origQty;
oldPrice = livePrice;
active = true;
}
} catch (err) {
console.log(err);
}
}
}
break;
default:
console.log("Final case: " + orderStatus.status);
break;
}
} catch (err) {
console.log(err);
}
}
});
}
/*
Algorithm:
1. Run websocket to recieve price in realtime
2. Check if the order is still active
3. If yes, and price is higher x%:
a. cancel old order
b. update new order
*/
我面临的错误是,即使 active 为 false,console.log("2) order ID: ...
仍会执行,如下图所示:
最佳答案
您的问题很可能源于共享单个变量 active
的多个异步函数。一些带有问题要点的伪代码:
function processAllOrders(symbol, active) {
client.doForAllOrdersWithSymbol(symbol, async (order) => {
console.log("Active before await: ", active)
if (active) {
const status = await order.getStatus() // execution waits here
// So active could have changed in the meantime...
console.log("Active after await: ", active)
if (status === 'whatever') {
active = false // <- changes active variable
}
}
})
}
由于该函数是为多个订单执行的,第一个随机到达的订单将更改所有订单的事件参数。由于您在第一个 console.log 之后有一个 await 语句,因此 active 的值可以在等待执行时更改。
关于javascript - 在 if 语句上使用 Promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55683141/