此函数像状态机一样按顺序处理股票帐户数据,以便下达卖出订单。
我需要将帐户数据传递到每个状态,并且我不想将其存储在全局变量中。我该如何实现这一目标?我是否不恰本地使用了 Promise?
请注意,每个调用(例如 get_account、delete_order)都是返回 Promise 的异步调用。他们不应该传递不相关的数据。
function sell_stocks(){
get_account_info().then(account => {
if (account.orders.length > 0){
return delete_orders(account.orders);
} else {
return "continue";
}
}).then(data => {
// Now I need variable "account"
place_sell_order(account.volume); //account undefined
}).catch(msg => {
//handle error
});
}
最佳答案
做什么
返回delete_orders(account.orders).then((data) => [data,account]);
还有
then(([数据, 帐户]) => {...})
或者如果您只想要帐户数据
返回delete_orders(account.orders).then(() => account);
还有
function sell_stocks(){
get_account_info().then(account => {
if (account.orders.length > 0){
return delete_orders(account.orders).then(()=> account);
} else {
return account;
}
}).then(account => {
place_sell_order(account.volume);
}).catch(msg => {
//handle error
});
}
或者使用异步/等待
async function sell_stocks(){
try {
const account = await get_account_info();
if (account.orders.length > 0) {
await delete_orders(account.orders)
}
return place_sell_order(account.volume);
} catch (e) {
console.log(`At sell_stocks ${e}`);
return null;
}
}
关于javascript - 如何随 promise 一起返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46743286/