获取范围外的API响应数据



我在React native应用程序中使用了AsyncStorage.所以我通过set AsyncStorage.setItem("@Token", jsonValue)设置了数据。我还创建了另一个get data函数因此,我无法在promise

范围外获取响应代码:

storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value);
await AsyncStorage.setItem("@Token", jsonValue);
} catch (e) {
// saving error
}
};
getData =   () => {
const getTodos =  AsyncStorage.getItem("@Token");
getTodos.the((res)=>{
return res;
})
if(res!==null){
return true;
}
else{

return false
}


}

Promise返回的值只能在它的.then()回调中访问。这意味着res只能在getTodos.then((res) => { ... })内部可用。

storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value);
await AsyncStorage.setItem("@Token", jsonValue);
} catch (e) {
// saving error
}
};
getData = () => {
const getTodos = AsyncStorage.getItem("@Token");
getTodos.then((res) => {
if (res !== null) {
return true;
} else {
return false;
}
});
};

看起来您希望getData从存储中返回项目。

试试这样

getData = async () => {
try {
const value = await AsyncStorage.getItem("@Token");
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};

试试这个:

getData =   () => {
try {
const getTodos =  AsyncStorage.getItem("@Token");
if (getTodos !== null) {
console.log(getTodos);
return true;
}
} catch (error) {
// Error retrieving data
return false;
}
}
}

最新更新