【发布时间】:2021-08-05 04:24:56
【问题描述】:
在循环中setItem 是否理想?假设我从后端检索了一个数据列表,我需要对每个数据进行一些繁重的处理,然后才能将其单独存储在 AsyncStorage 存储中。
import { AsyncStorage } from "react-native";
async function getList(query){
/* some call setup in here */
try {
const response = await fetch(/* call parameters in here */);
const { data, err } = response;
if (err) throw new Error(err.message);
await processAndStoreItems(data);
return data;
} catch(err){
throw err;
}
}
async function processAndStoreItems(data){
/* data is a list of array that needs to be processed first before storing */
data.forEach( d => {
/* Some processing of data happening in here, and it may be a heavy processing that may take time */
const { processedKey, processedData } = await heavyProcessingHere(d);
await AsyncStorage.setItem(processedKey, JSON.stringify(processedData));
});
}
我这样做的原因是,某些过程可能需要更长的时间,并且等待整个过程完成然后只存储的想法并不理想,因为可能存在用户退出的情况整个过程仍在运行的应用程序,我需要在注销时清除存储的项目。
如果我在循环内执行setItem,至少我可以确信存储将始终针对任何已完成的处理数据进行更新,并且我可以删除已在注销时存储的任何内容,而不是等待整个进程完成,然后仅将其存储在 AsyncStorage 中,如果用户在进程仍未完成的情况下注销,这将是一个问题,使存储过时并且难以删除仍在处理中的项目。
所以我需要知道性能是否明智,在循环内使用setItem 可以吗?我从某处读到有人在尝试使用 setItem 内部循环时遇到 AsyncStorage 崩溃问题,这对我不利。
【问题讨论】: