提问者:小点点

NodeJS:异步函数的保证顺序


如何确保第二个函数调用是在第一个函数调用执行完毕后启动的呢?

const asyncFuntion = async (callNumber: string, timeout: number) => {
    await setTimeout(() => {
        console.log(`call: ${callNumber}`, timeout);
    }, timeout);
};

asyncFuntion("1", 100);
asyncFuntion("2", 50);

当前控制台输出:

call: 2 50
call: 1 100

所需控制台输出:

call: 1 100
call: 2 50

共3个答案

匿名用户

AwaitSetTimeout()没有影响,因为它不返回承诺。

因此,该问题的解决方案是使用promise包装setTimeout

另外,如果您希望第一个函数调用在第二个函数调用之前执行,请在调用第二个函数之前创建承诺并解决它们,并对第一个函数调用使用await

看看下面的实现:

null

const asyncFuntion = async (callNumber, timeout) => {

    return new Promise( async (resolve, reject) => { 
        await setTimeout(() => {
            console.log(`call: ${callNumber}`, timeout);
            resolve();
        }, timeout); 
    });
};

async function test() {

    /*Write the function calls in the order you want them to get executed*/
    await asyncFuntion("1", 100);
    await asyncFuntion("2", 50);
}

test();

匿名用户

有两件事需要注意。

>

  • SetTimeout前面使用Await无效。它只适用于返回承诺的函数。

    setTimeout的执行顺序只取决于时间间隔,而不取决于另一个迭代。

    100ms的间隔不可能在50ms的间隔之前做一些事情。如果您希望第二个调用一直等待到第一个调用完成,请创建一个承诺并在调用第二个之前解决它。

  • 匿名用户

    另一种操作setTimeout计时器的方法,虽然不那么优雅,但也很有效。

    let timer = 0
    const asyncFuntion = (callNumber, timeout) => {
        timer += timeout
        setTimeout(() => {
            console.log(`call: ${callNumber}`, timeout);
        }, timer);
    };
    
    
    asyncFuntion("1", 100);
    asyncFuntion("2", 50);
    

    相关问题