首页 > 解决方案 > 循环内的 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 崩溃问题,这对我不利。

标签: react-nativeasyncstorage

解决方案


为什么你不把你的数组放到 cookie 中

像这样;

await AsyncStorage.setItem(dataArray, JSON.stringify(data));

推荐阅读