Javascript等待/异步-这会导致竞争状况吗?

时间:2019-01-03 03:58:35

标签: 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循环迭代中导致奇怪的结果?

1 个答案:

答案 0 :(得分:2)

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

相关问题