首页 > 解决方案 > 重复异步函数直到为真

问题描述

我有一个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()从另一个函数调用,在那里我想检查它的返回值(truefalse)并在以下情况下继续代码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()变成什么。

我怎样才能达到预期的行为?

标签: javascriptnode.jsasync-awaitpromise

解决方案


您可以使用这样的递归功能:

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();

推荐阅读