react-native - 循环内的 AsyncStorage setItem
问题描述
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 崩溃问题,这对我不利。
解决方案
为什么你不把你的数组放到 cookie 中
像这样;
await AsyncStorage.setItem(dataArray, JSON.stringify(data));
推荐阅读
- shell - 打印 CSV 的前 N 行,其中引用的字段可以包含换行符
- php - 持久连接 - 表插入
- javascript - 如何使用不同的 API Javascript 映射日期
- c - 如何在 C 中使用浮点数和整数进行数学运算
- java - 为什么双除法返回一个非常错误的值?
- mysql - 选择每天每笔交易的总和和计数并显示它
- date - TYPO3 - 流体中的明天日期
- html - 创建响应式汉堡菜单
- google-sheets - 为当前单元格设置默认值 Google 电子表格
- scatter-plot - 想要在 Matplotlib 中的一个图中显示 76 个散点图,其中每个散点图的标题将基于字典中的键