2017-11-21 10 views
-1

일부 Utils 기능으로 Storage.js 파일을 만듭니다. 대부분의 경우 , 난이 방법 비동기 된 SomeFuncion() =>에서 사용됩니다 {하자 foo는 = getOnDevice (someName) 기다리고} 하지만 내 경우에는 내가 구문 가져 오기 비동기 함수를 사용하는 방법은 무엇입니까?

import {AsyncStorage} from 'react-native' 
 

 
export const saveOnDevice = async (name, data) => { 
 
\t try { 
 
\t \t if (data !== null && data !== undefined) { 
 
\t \t \t await AsyncStorage.setItem(name, JSON.stringify(data)); 
 
\t \t } 
 
\t } catch (error) { 
 
\t \t console.log(error) 
 
\t } 
 
}; 
 

 
export const getOnDevice = async (name) => { 
 
\t try { 
 
\t \t const data = await AsyncStorage.getItem(name); 
 
\t \t if (data !== null && data !== undefined) { 
 
\t \t \t return data 
 
\t \t } 
 
\t } catch (error) { 
 
\t \t console.log(error) 
 
\t } 
 
};

에 문제가를

어떻게 비동기 함수를 선언하지 않고 사용할 수 있습니까?

import {saveOnDevice} from '../../utils/Storage' 
 
export function fetchUrlWithRedux(url) { 
 
\t return (dispatch) => { 
 
\t \t dispatch(fetchUrlRequest(url)); 
 
\t \t return fetchUrl(url, dispatch).then(([response, json]) => { 
 
\t \t \t if (response.status === 200) { 
 
\t \t \t \t saveOnDevice('url', json.data.host); 
 
\t \t \t \t dispatch(fetchUrlSuccess(json)) 
 
\t \t \t } 
 
\t \t \t else { 
 
\t \t \t \t dispatch(fetchUrlError()) 
 
\t \t \t } 
 
\t \t }).catch(() => dispatch(fetchUrlError())) 
 
\t } 
 
}

내 코드에 어떤 문제가 있습니까?

saveOnDevice()에 호출하기 전에 당신이 .then()에 전달 된 익명 함수 이전 async을 추가 할 필요가 있다고 생각

답변

0

당신이 async/await를 사용하지 않을 경우 당신의 주 파일은 다음과 같이 약속을 사용할 수 있습니다.

saveOnDevice('url', json.data.host).then(() => { 
    dispatch(fetchUrlSuccess(json)) 
}) 
0

감사하고, 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())) 
    } 
}