首页 > 解决方案 > Javascript 等待/异步 - 这会导致竞争条件吗?

问题描述

假设我有一个使用 Socket.IO 的 nodeJS 服务器。一个监听器是异步的,像这样:

let aHugeArray = new Array(50000000);
// ... fill the array with data...

// print the array asynchronously:
socket.on('print-array', async () => {
    let isFinished = await printArray();
});

// remove an item from the array:
socket.on('remove-from-array', (item : any) => {
    let index = aHugeArray.indexOf(item);
    aHugeArray.splice(index, 1);
});

private async printArray() : Promise<boolean> {
    for (let i = 0; i < aHugeArray.length; i++) {
        console.log(aHugeArray[i]);
    }
    return true;
}

假设我调用print-array然后立即调用remove-from-array(它将在print-array完成循环遍历数组之前执行。在这种情况下会发生什么?会在循环完成之前remove-from-array阻止回调操作aHugeArray吗?或者数组会被操作,可能会导致奇怪的结果其余的print-array循环迭代?

标签: javascripttypescriptasync-await

解决方案


print-array 函数不是异步的,所以除非你有很多内存,否则在等待运行 remove-from-array 时抓取它的内容并记录它们不会明显阻塞线程

如果你有一个功能需要在某事完成之前完成,那么就承诺它

const IMightTakeSomeTime = new Promise ((resolve, fail) => {
    setTimeout(() => {
        resolve(console.log('i am finished'))
    }, 3000);
})

IMightTakeSomeTime.then(() => 
    console.log('Now its my time to shine')
)

或者你可以使用 async / await 如果你想花哨

const IMightTakeSomeTime = new Promise ((resolve, fail) => {
    setTimeout(() => {
        resolve(console.log('i am finished'))
    }, 3000);
})

const run = async () => {
    await IMightTakeSomeTime
    console.log('Now its my time to shine')
}

run()

如果您想查看众所周知的非异步线程阻塞函数,请查看 Node.js fs 库的同步版本,其中有一些不需要等待的函数的“同步”版本

https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options


推荐阅读