在if语句上使用Promises

时间:2019-04-15 05:41:03

标签: javascript node.js promise callback async-await

我正在尝试在if条件下使用Promises。我面临的问题是,即使if语句为false,它下面的代码仍然会执行。我该如何解决这个错误?

此处为示例,但链接中的完整代码为: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: ...仍会执行,如下图所示: enter image description here

1 个答案:

答案 0 :(得分:1)

您的问题很可能是由于共享单个变量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的值可以更改。