Search code examples
javascriptreact-nativeasync-awaitasyncstorage

How do I store a promise object inside a variable


I want to know how I can store a promise as an object inside a variable

My Code


Read and Write Functions

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);
        });
    });
}

My object which is being stored and how I'm calling my functions

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);

I'm using the following library if some reference is required, this is for a react native expo project


Solution

  • Assuming you want to store read promise, since you're returning a promise in read function, you can directly store promise by

    readPromise = read("tasks@today");
    

    readPromise variable will be a promise object