异步更新数组



是否可以异步更新Java脚本数组?它应该看起来像这样:

export const main = async () => {
let array = []
const update = async() => {
//this should update the array every "interval"-seconds              
}
update();
setInterval(update, interval);
const usage = async() => {
//this uses the array every n-seconds             
}
usage();
setInterval(usage, n);

update函数调用async函数来获取数据,并且应该替换数组中的旧数据,数组总是具有相同的大小

添加不必要的异步逻辑可能会导致您的函数实际运行速度变慢。因此,了解什么时候应该使用它是很重要的。

例如,如果你在一个数组上做了很多工作(例如,在一个数组上循环1000个元素等)或从服务器上获取数据,异步逻辑将使你的代码运行得更快,因为浏览器可以确保任务是非阻塞的。如果不是,最好的办法是保持同步。

注意:Javascript不能同时运行脚本。它是一种单线程语言。要在浏览器上模拟并发,您可以查看浏览器提供的Webworkers API。通过让一个脚本在另一个cpu线程上运行,它允许你以并发方式运行javascript,但也有限制。

然而,繁重的数据预处理任务需要在客户端完成(如修改大数组),这是像Webworkers这样的东西。都是值得的。

推荐:

由于您在更新时获取数据,下面是一个用于将此异步逻辑写入的模板。我使用axios作为获取数据的一个例子,但你可以初始化一个http请求在任何形式你认为最好的。

import axios from "axios"
//will auto update when changed, and value will be exported
let array = []
export {array}
export const main = async () => {
//this should update the array every "interval"-seconds  
const update = async(array) => {
const updated_arr = await axios.get(url)
//perform async updating logic on updating array with 
//updated_arr.data.pop(), updated_arr.data.shift(), fetching data, etc.

//assign your updated array back to array, so it updates
array = updated_arr.data            
}
setInterval(update, interval);
}

将update()和usage()函数移出main()函数,如下所示:

const update = async(array) => {
array.push("newValue") 
return array;
}
const usage = async(array) => {
return array;          
}
export const main = async () => {
let array = [];
const upd_interval = 10;
const use_interval = 20
setInterval(await update(array), upd_interval));
setInterval(await usage(array, use_interval));
}

最新更新