由于某种原因,每次我运行此代码时,都会出现“ 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);
我似乎找不到问题。有任何想法吗?
你有几个不同的问题。正如其他人已经指出的那样,你不会从该makeBuy()
方法中返回承诺。但是,这似乎并不像简单地添加return
建议的语句那样容易。这是因为看来你实际上需要等待内部承诺从解析为真,client.placeActiveOrder()
然后再设置hasPosition
为true。
因此,你有两种选择(建议使用#2):
.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);
});
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);