使用async和await与export const

时间:2018-06-11 18:45:20

标签: javascript reactjs react-native

我无法完成这项工作......它说:await是一个保留词。是的,当然是......而且我想使用:)

出了什么问题?

export const loginWithToken = async () => {
  return dispatch => {
    dispatch({type: SESSION_LOGIN_IN_PROGRESS, payload: true})
    let storedData = await ReadFromLocalDB('user')
    console.log(storedData)
    if (!storedData) {
        invalidToken(null, dispatch)
    }
    else {
        storedData = JSON.parse(storedData)
        SessionLoginWithToken(storedData.session.token).then(res => {
            console.log(res)
            loginSuccessfully(res, dispatch, true)
        })
    }
  }
}

我的ReadFromLocalDB是这样的:

export const ReadFromLocalDB = async (key) => {
   return AsyncStorage.getItem(key)
}

它返回了一个承诺

3 个答案:

答案 0 :(得分:8)

return dispatch => {...}也需要async我相信。现在,只有顶级函数是async,而不是嵌套函数。

// This function is async
export const loginWithToken = async () => {
  // This one is not though which means it can't use await inside
  // return dispatch => {

  // Instead it should likely be:
  return async dispatch => {
    dispatch({type: SESSION_LOGIN_IN_PROGRESS, payload: true})
    let storedData = await ReadFromLocalDB('user')
    console.log(storedData)
    if (!storedData) {
        invalidToken(null, dispatch)
    }
    else {
        storedData = JSON.parse(storedData)
        SessionLoginWithToken(storedData.session.token).then(res => {
            console.log(res)
            loginSuccessfully(res, dispatch, true)
        })
    }
  }
}

答案 1 :(得分:1)

看起来这是因为您返回的函数(dispatch => {...})不是异步函数,因此您不能在其中使用await。您需要执行return async dispatch => {...}

之类的操作

答案 2 :(得分:1)

对于导出和导入,建议遵循以下模型:

要在文件myFile.js中定义和导出函数:

export const request = async (arg1, arg2) => {
  try {
    const response = await fetch('https://api.com/values/?arg1=' + arg1 + '&arg2=' arg2);
    const json = await response.json();
    console.log(json);
  }
  catch (e) {
    console.log('We have the error', e);
  }
}

要导入并应用该功能,

import {request} from './myFile'

request();