Javascript await/async - 这会导致竞争条件吗?

标签 javascript typescript async-await

假设我有一个使用 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 循环迭代中导致奇怪的结果?

最佳答案

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

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

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

关于Javascript await/async - 这会导致竞争条件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54016165/

相关文章:

javascript - 导航时是否可以防止破坏Angular组件?

reactjs - 我如何将嵌套的 promise 传递给异步等待

c# - 在异步方法中处理空任务的最佳方法?

javascript - 使用 Promise.all 等待没有生效

angularjs - Chrome 开发工具未映射 ts 源

javascript - 我如何从 firestore 获取多个文档

javascript正则表达式在char一次拆分匹配,而不是多个

javascript - 当多个表单位于同一页面时,WTForms 提交表单两次

typescript - VSCode : Tests won't proceed after using executeCommand to open a sample project

javascript - 简单的 orderBy 过滤器在 AngularJs 中不起作用