嗨,我有一个从共享首选项返回值的函数,但是最初它返回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
我在哪里错了
答案 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');
});
}