Warm tip: This article is reproduced from serverfault.com, please click

javascript-TypeError:无法读取算法交易中未定义的属性“ then”

(javascript - TypeError: Cannot read property 'then' of undefined in Algorithmic Trading)

发布于 2020-11-29 02:20:27

由于某种原因,每次我运行此代码时,都会出现“ TypeError:无法读取未定义的属性'then'”错误。我不明白为什么。这是代码:

console.log("BUY");
exchange.marketBuy()
.then(res => {
console.log("Buy successful");
hasPosition = true
setTimeout(strategy, 1000)
})
.catch(console.error);

marketBuy()函数是

    marketBuy() {
    client.getLatestInformation()
    .then(response => {
      var price = response.result[0].last_price;
      client.placeActiveOrder({
       side: "Buy",
       symbol: "BTCUSD",
       order_type: "Market",
       qty: 20,
       time_in_force: "GoodTillCancel",
       take_profit: price * 1.5,
       stop_loss: price / 1.5})
      .then(response => console.log(response))

    })

我试过了

console.log("BUY");
exchange.marketBuy()
.then(res => {
hasPosition = true
setTimeout(strategy, 1000)
return Promise.resolve(console.log("Buy successful"));
})
.catch(console.error);

我似乎找不到问题。有任何想法吗?

Questioner
R123456789
Viewed
0
Randy Casburn 2020-11-29 10:49:12

你有几个不同的问题。正如其他人已经指出的那样,你不会从该makeBuy()方法中返回承诺但是,这似乎并不像简单地添加return建议语句那样容易这是因为看来你实际上需要等待内部承诺从解析为真client.placeActiveOrder()然后再设置hasPosition为true。

因此,你有两种选择(建议使用#2):

  1. 将必须等待内部承诺解决的代码移到.then()内部承诺的上(这样会给hasPosition变量带来问题):
client.placeActiveOrder({
       side: "Buy",
       symbol: "BTCUSD",
       order_type: "Market",
       qty: 20,
       time_in_force: "GoodTillCancel",
       take_profit: price * 1.5,
       stop_loss: price / 1.5})
      .then(response => {
         console.log(response);
         console.log("Buy successful");
         hasPosition = true;
         setTimeout(strategy, 1000);
         });
  1. 使用async / await使你的代码看起来像工作流程:
    async marketBuy() {
      const response = await client.getLatestInformation();
      const price = response.result[0].last_price;
      const order = await client.placeActiveOrder({
        side: "Buy",
        symbol: "BTCUSD",
        order_type: "Market",
        qty: 20,
        time_in_force: "GoodTillCancel",
        take_profit: price * 1.5,
        stop_loss: price / 1.5
      })
      return order;
    }

建议使用第二种选择,因为它可以让你以预期的方式进行工作。这是将不再引发错误的调用代码:

    console.log("BUY");
    exchange.marketBuy()
      .then(res => { // res here is the order returned
        console.log("Buy successful");
        hasPosition = true
        setTimeout(strategy, 1000)
      })
      .catch(console.error);