javascript - 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
循环迭代?
解决方案
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
推荐阅读
- node.js - 结合多个 async/await 调用的结果
- arrays - 如何保存数组。所以App重启后也是一样
- c# - Extent 报告 Selenium WebDriver 屏幕截图加载问题 c#
- jquery - jQuery $ 不适用于 Sufee
- android - 无法解析方法createstatement Android Studio
- php - Error updating record: You have an error in your SQL syntax how can i solve it?
- php - PHP PDO Sqlsrv always return every values as string
- javascript - vuejs on scroll 修复侧边栏,
- oracle - 有人可以解释mysql和Oracle之间的数据库概念区别吗?
- angular - Angular 6 mouseenter 被触发而不是点击事件