首页 > 解决方案 > 如何将承诺对象存储在变量中

问题描述

我想知道如何将承诺作为对象存储在变量中

我的代码


读写函数

async function storage(data, key) {
    await AsyncStorage.setItem(`${key}`, JSON.stringify(data));
}

async function read(key) {
    return new Promise((resolve, reject) => {
        AsyncStorage.getItem(`${key}`, (err, data) => {
            if (err) reject(err);
            resolve(data);
        });
    });
}

我正在存储的对象以及我如何调用我的函数

let testing = {
    swipe1: {
        key: 1,
        text: "Swipe1Text changed",
    },
    swipe2: {
        key: "2",
        text: "Swipe2Text",
    },
};

storage(testing, "tasks@today");

// I'm able to console.log the following

let readStorageSwipes = read("tasks@today").then((result) => {
    return result;
});
console.log(readStorageSwipes.swipe1);

如果需要一些参考,我正在使用以下库,这是一个 react native expo 项目

标签: javascriptreact-nativeasync-awaitasyncstorage

解决方案


假设你想存储读取承诺,因为你在读取函数中返回一个承诺,你可以直接存储承诺

readPromise = read("tasks@today");

readPromise变量将是一个承诺对象


推荐阅读