【问题标题】:How do I store a promise object inside a variable如何将承诺对象存储在变量中
【发布时间】:2021-03-10 13:43:45
【问题描述】:

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

我的代码


读写函数

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

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

【问题讨论】:

  • 你在 readStorageSwipes 变量中保存了承诺吗?
  • @Bergi 对不起,我应该很清楚,我想将 Promise 作为对象存储在变量中
  • 正在在变量中存储promise,这是一个带有.then.catchfinally 方法的对象。你的意思是你想在变量中存储承诺的结果,它实现的对象?然后你需要等待承诺,await.then()
  • @Bergi 是的,但这不是我在做什么吗?

标签: javascript react-native async-await asyncstorage


【解决方案1】:

假设你想存储读取的promise,由于你在读取函数中返回了一个promise,你可以直接存储promise by

readPromise = read("tasks@today");

readPromise 变量将是一个承诺对象

【讨论】:

  • 对不起,我应该清楚,我想将该承诺作为对象存储在变量中
  • 也许您可以解释一下您对 Promise 对象所做的工作。目前还不清楚你想要实现什么。
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多