2017-11-01 7 views
0

다른 함수에서 AsyncStorage에 저장된 값을 사용하고 싶습니다.약속 대신 AsyncStorage (getItem)에서 키 값 반환

는 여기가 AsyncStorage에 저장된 savedValue 그렇다고 값을 얻기 위해 위의 기능 getSavedValue()를 만들어 내 ValueHandler.js

import { AsyncStorage } from 'react-native'; 

export async function getSavedValue() { 
    try { 
    const val = await AsyncStorage.getItem('@MyStore:savedValue'); 
    console.log("#getSavedValue", val); 
    return val; 
    } catch (error) { 
    console.log("#getSavedValue", error); 
    } 
    return null; 
} 

입니다.

import {getSavedValue} from '../lib/ValueHandler'; 
import Api from '../lib/Api'; 

export function fetchData() { 
    return(dispatch, getState) => { 
    var params = [ 
     'client_id=1234567890', 
    ]; 
    console.log("#getSavedValue()", getSavedValue()); 
    if(getSavedValue() != null) { 
     params = [ 
     ...params, 
     'savedValue='+getSavedValue() 
     ]; 
    } 
    params = params.join('&'); 
    console.log(params); 
    return Api.get(`/posts/5132?${params}`).then(resp => { 
     console.log(resp.posts); 
     dispatch(setFetchedPosts({ post: resp.posts })); 
    }).catch((ex) => { 
     console.log(ex); 
    }); 
    } 
} 

어떻게해야합니까? 로컬 저장소에 값을 저장하고 API 호출을해야 할 때 간단히 검색 할 수있는 간단한 방법이 필요했습니다.

누구든지 이에 대한 제안이나 해결책이 있습니까?

+0

나는 문제가 가정 답변을 게시에 그래서 당신을 기다리고 있습니다 return (dispatch, getState) => {async 추가를 호출을 가져 오는 것은 키 (asyncStorage에 저장된 값)가 검색되기 전에 수행됩니다 (asyncStorage에서의 검색은 비동기 임). Plz은 질문이 잘 설명되지 않았기 때문에 문제가 다른 것이라면 저에게 맞습니다 :) –

+1

async functions as a promise ... async/await는 약속을위한 설탕 ... 값을 얻으려면, getSavedValue를 호출하는 함수가'async'가 아니기 때문에 당신은 오래된 학교 약속 구문 인'getSavedValue(). then (value =>/*)를 정의 할 것입니다. 여기에 여기있는 값을 사용하세요 * /)' –

+0

@ JaromandaX- 알겠습니다. 나는 then() 부분에서 그것을 사용하는 일반적인 방법을 알고있다. 나는 값으로 저장하고 직접 액세스하는 직접적인 방법을 원했다. 어쨌든 고마워. –

답변

0

이 같은 수행 할 수 있습니다

import { AsyncStorage } from 'react-native'; 

export async function getSavedValue() { 
    return new Promise ((resolve, reject) => { 
     try { 
     const val = await AsyncStorage.getItem('@MyStore:savedValue'); 
     console.log("#getSavedValue", val); 
     resolve(val); 
     }catch (error) { 
     console.log("#getSavedValue", error); 
     reject(error) 
     } 
    }) 
} 


import {getSavedValue} from '../lib/ValueHandler'; 
import Api from '../lib/Api'; 

export function fetchData() { 
    return async (dispatch, getState) => { 
    var params = [ 
     'client_id=1234567890', 
    ]; 
    console.log("#getSavedValue()", getSavedValue()); 
    if(getSavedValue() != null) { 
     params = [ 
     ...params, 
     'savedValue='+ await getSavedValue() 
     ]; 
    } 
    params = params.join('&'); 
    console.log(params); 
    return Api.get(`/posts/5132?${params}`).then(resp => { 
     console.log(resp.posts); 
     dispatch(setFetchedPosts({ post: resp.posts })); 
    }).catch((ex) => { 
     console.log(ex); 
    }); 
    } 
} 
+0

작동하지 않습니다. "WorkerGlobalScope"에서 'importScripts'를 실행하지 못했습니다.이 에러는 대개 aswait이 async없이 사용되었을 때 발생합니다 .. –

+0

'fetchData'에'async'를 추가하면'fetchData'가 Promise를 리턴하고 내부에서 async를 사용할 수 있습니다. 'fetchData' .... 문제는'fetchData'를 호출하여 반환 된 함수에'await'가 추가 된 것입니다. 아마도 return async (dispatch, getState) => {'도움이 될 것입니다. –

+0

예, –

0

이 시도 :

그것이

import {getSavedValue} from '../lib/ValueHandler'; 
import Api from '../lib/Api'; 

export function fetchData() { 
    return async (dispatch, getState) => { 
     let params = [ 
      'client_id=1234567890', 
     ]; 
     const val = await getSavedValue(); 
     if (val != null) { 
      params = [...params, 'savedValue='+val]; 
    // why not 
    //  params.push(`savedValue=${val}`); 
    // 
     } 
     params = params.join('&'); 
     return Api.get(`/posts/5132?${params}`)) 
     .then(resp => { 
       dispatch(setFetchedPosts({ post: resp.posts })); 
     }) 
     .catch((ex) => { 
      console.log(ex); 
     }); 
    }; 
}