我用某些UTILS功能制作了一个Storage.js
文件。在大多数情况下,我以这种方式使用它:
async someFunction()=>{ let foo = await getOnDevice(someName)}
但是,在我的情况下,我对语法有问题
import {AsyncStorage} from 'react-native'
export const saveOnDevice = async (name, data) => {
try {
if (data !== null && data !== undefined) {
await AsyncStorage.setItem(name, JSON.stringify(data));
}
} catch (error) {
console.log(error)
}
};
export const getOnDevice = async (name) => {
try {
const data = await AsyncStorage.getItem(name);
if (data !== null && data !== undefined) {
return data
}
} catch (error) {
console.log(error)
}
};
如何在不声明async
函数的情况下使用它?
import {saveOnDevice} from '../../utils/Storage'
export function fetchUrlWithRedux(url) {
return (dispatch) => {
dispatch(fetchUrlRequest(url));
return fetchUrl(url, dispatch).then(([response, json]) => {
if (response.status === 200) {
saveOnDevice('url', json.data.host);
dispatch(fetchUrlSuccess(json))
}
else {
dispatch(fetchUrlError())
}
}).catch(() => dispatch(fetchUrlError()))
}
}
我的代码怎么了?
如果您不想在主文件中使用async/await
,则可以使用Promise,如下。
saveOnDevice('url', json.data.host).then(() => {
dispatch(fetchUrlSuccess(json))
})
我认为您需要在传递给 .then()
的匿名函数之前添加 async
,然后在致电到 saveOnDevice()
之前 await
:
import {saveOnDevice} from '../../utils/Storage'
export function fetchUrlWithRedux(url) {
return (dispatch) => {
dispatch(fetchUrlRequest(url));
return fetchUrl(url, dispatch).then(async ([response, json]) => {
if (response.status === 200) {
await saveOnDevice('url', json.data.host);
dispatch(fetchUrlSuccess(json))
}
else {
dispatch(fetchUrlError())
}
}).catch(() => dispatch(fetchUrlError()))
}
}