无法读取带有承诺的未定义属性“ then”

时间:2018-11-20 14:33:56

标签: javascript reactjs react-native promise async-await

嗨,我有一个从共享首选项返回值的函数,但是最初它返回null / undefined的原因是由于承诺或从共享首选项返回的数据最初没有任何内容。

export function getSharedPreferenceValue( key ) {
    SInfo.getItem(key, {
        sharedPreferencesName: sharedPreferenceName,
                keychainService: keyChainServiceName}).then(value => {
                    consoleLog('getSharedPreferenceValue - ' + key + ' - ' + value) //value 1
                    if( typeof value === 'undefined'){
                        return 'true';
                    }else{
                        return value;                    
                    }                    
                });
}

并像这样使用它

   whereShoulINavigateTo = async () => {
        const returned = await getSharedPreferenceValue( globals.SHARED_PREFERENCES_KEY_FIRST_LAUNCH).then ((isFirstLaunch) => {
            consoleLog('isFirstLaunch - ' + isFirstLaunch); 
            consoleLog('isFirstLaunch - ' + typeof isFirstLaunch); 
            //do something based on the value
        });
    }

错误是

TypeError: Cannot read property 'then' of undefined TypeError: Cannot read property 'then' of undefined

我在哪里错了

1 个答案:

答案 0 :(得分:1)

尝试返回承诺:

export function getSharedPreferenceValue(key) {
    dataObj = {
        sharedPreferenceName: sharedPreferenceName,
        keychainService: keyChainServiceName
    };

    return new Promise((res, rej) => {
        SInfo.getItem(key, dataObj).then(value => {
            console.log(`{key} {value}`);
            if (typeof value === 'undefined') {
                res('true');
            } else {
                rej(value)
            }
        });
    });
}

然后相应地修改第二个功能。

whereShoulINavigateTo = async () => {
    getSharedPreferenceValue(globals.SHARED_PREFERENCES_KEY_FIRST_LAUNCH).then((isFirstLaunch) => {
        console.log(`{isFirstLaunch}`);
    }).catch((value) => {
        console.log('Failed');
    });
}