javascript - 重复异步函数直到为真
问题描述
我有一个async
检查订单状态的函数(checkOrderStatus()
)。我想重复这个函数,直到它返回"FILLED"
or "CANCELED"
,然后在另一个函数中使用这个返回值来决定继续或停止代码。"FILLED"
每个订单在或之前都会经历不同的状态"CANCELED"
,因此需要重复该checkOrderStatus()
函数(这是一个 API 调用)。
我现在拥有的是这个,重复这个checkOrderStatus()
功能:
const watch = filter => {
return new Promise(callback => {
const interval = setInterval(async () => {
if (!(await filter())) return;
clearInterval(interval);
callback();
}, 1000);
});
};
const watchFill = (asset, orderId) => {
return watch(async () => {
const { status } = await checkOrderStatus(asset, orderId);
console.log(`Order status: ${status}`);
if (status === 'CANCELED') return false;
return status === 'FILLED';
});
};
然后我watchFill()
从另一个函数调用,在那里我想检查它的返回值(true
或false
)并在以下情况下继续代码true
或在以下情况下停止代码false
:
const sellOrder = async (asset, orderId) => {
try {
const orderIsFilled = await watchFill(asset, orderId);
if (orderIsFilled) {
//… Continue the code (status === 'FILLED'), calling other async functions …
}
else {
//… Stop the code
return false;
}
}
catch (err) {
console.error('Err sellIfFilled() :', err);
}
};
但是,这不起作用。console.log
我可以通过in看到终端中正在更新的状态watchFill()
,但它永远不会停止,最重要的是,orderIsFilled
变量 in中的值sellOrder()
不会更新,无论返回的值watchFill()
变成什么。
我怎样才能达到预期的行为?
解决方案
您可以使用这样的递归功能:
const checkOrderStatus = async () => {
// ... function does some work ...
await someOtherFunction() // you can use here the other async function as well
// ... function does some more work after returning from await ...
if(/* if status is FILLED or CANCELED */) {
// return true or false or some info about response for your needs
} else {
checkOrderStatus();
}
}
// this will response back when status will be FILLED or CANCELED
await checkOrderStatus();
推荐阅读
- javascript - 无法读取未定义的属性“isLoggedIn”
- filter - 如何设计d类输出滤波器(有源滤波器)?
- spring-boot - springboot jdbctemplate string concat 失败并出现错误“Missing IN or OUT parameter at index :: 2”
- mysql - Mysql查询在日期分组时没有给出任何结果
- ruby-on-rails - Ruby on rails 表单错误未显示
- reactjs - 嵌套 React Context Provider 并使用 useContext 是一个问题吗?
- c# - X。Equals(null) 返回 false(仅适用于不可为空的值类型)
- python - 使用 python 2 运行脚本时出现语法错误
- react-native - React Native 上的 MobX 反应状态
- android - 从 url 获取图像并在图像视图中显示时调整图像大小