【问题标题】:How use import async function?如何使用导入异步功能?
【发布时间】:2017-11-21 16:56:00
【问题描述】:

我制作了一个带有一些 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()))
	}
}

我的代码有什么问题?

【问题讨论】:

    标签: javascript asynchronous react-native import asyncstorage


    【解决方案1】:

    如果您不想在主文件中使用async/await,则可以使用 promise,如下所示。

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

    【讨论】:

      【解决方案2】:

      我认为您需要在传递给.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()))
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-25
        • 2016-11-27
        • 2020-05-16
        • 2021-12-29
        • 2019-11-01
        • 1970-01-01
        • 2021-12-14
        • 2018-01-15
        • 1970-01-01
        相关资源
        最近更新 更多