Javascript TypeError:无法读取属性';然后';算法交易中未定义的
出于某种原因,每次运行此代码时,我都会捕获“TypeError:cannotreadproperty'then'of undefined”错误。我不明白为什么。代码如下:Javascript TypeError:无法读取属性';然后';算法交易中未定义的,javascript,algorithmic-trading,Javascript,Algorithmic Trading,出于某种原因,每次运行此代码时,我都会捕获“TypeError:cannotreadproperty'then'of undefined”错误。我不明白为什么。代码如下: console.log("BUY"); exchange.marketBuy() .then(res => { console.log("Buy successful"); hasPosition = true setTimeout(strategy, 1000) }) .catc
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
语句那么容易。这是因为在将hasPosition
设置为true之前,您实际上需要等待内部承诺从client.placeActiveOrder()
解析
因此,您有两种选择(建议选择2):
.then()
(这会在hasPosition
变量中产生问题): 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);
欢迎来到StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。如何提问适用于这里。StackOverflow不是设计、编码、研究、调试或教程服务。marketbuy函数需要返回一个承诺,以便调用
marketbuy()。然后()
。目前它不返回任何内容。您需要在第一行添加return
关键字<代码>函数marketBuy(){return client.getLatestInformation()。然后(…
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);