Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【提问】如何封装使用 AsyncStorage #139

Open
imzyf opened this issue Aug 29, 2017 · 2 comments
Open

【提问】如何封装使用 AsyncStorage #139

imzyf opened this issue Aug 29, 2017 · 2 comments

Comments

@imzyf
Copy link

imzyf commented Aug 29, 2017

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 没有办法封装吗,只能哪里调用写哪里?

@ckinmind
Copy link
Owner

ckinmind commented Aug 29, 2017

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

貌似是通过callback

@imzyf
Copy link
Author

imzyf commented Aug 30, 2017

找到了一种方式:使用 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);
            }
        });
    });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants