由于某种原因,每次运行此代码时,我都会捕获"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()
方法返回promise。但是,它似乎并不像建议的那样简单地添加一个return
语句那么容易。这是因为在将hasPosition
设置为true之前,您实际上需要等待内部promise从client.placeActiveOrder()
解析。
所以你有两个选择(推荐#2(:
- 将必须等待内部promise解决的代码移动到内部promise的
.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/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);