ReactCollect icon indicating copy to clipboard operation
ReactCollect copied to clipboard

【提问】如何封装使用 AsyncStorage

Open imzyf opened this issue 7 years ago • 2 comments

AsyncStorage 因为是异步的,怎么封装呢?比如:


    getxxx() {
        AsyncStorage.getItem(AsyncStorageKey.xxx, (error, result) => {
            if (!error) {
                
                if (result !== null && result !== '') {
                    return JSON.parse(result);
                }
            } else {
                return false;
            }
        })
    }

将这个方法放在一个 class 中,然后在别的 class,new 这个 class,调用 getxxx 得到的是 undefined,但是其实是有值的,AsyncStorage 没有办法封装吗,只能哪里调用写哪里?

imzyf avatar Aug 29 '17 11:08 imzyf

@imzyf 我百度了下AsyncStorage这个好像是react native里面的,我对这个没研究,给你找了fb的官方文档,貌似有解决方法: asyncstorage

貌似是通过callback

ckinmind avatar Aug 29 '17 16:08 ckinmind

找到了一种方式:使用 Promise

getSubscribeCategoryId() {
    return new Promise((resolve, reject) => {
        AsyncStorage.getItem(AsyncStorageKey.xxx, (error, result) => {
            if (!error && result !== null && result !== '') {
                try {
                    resolve(JSON.parse(result));
                } catch (e) {
                    reject(error);
                }
            } else {
                reject(error);
            }
        });
    });
}

imzyf avatar Aug 30 '17 06:08 imzyf