将 async 和 await 与 export const 一起使用

IT技术 javascript reactjs react-native
2021-05-18 20:49:14

我无法完成这项工作......它说: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)
}

它返回一个Promise

3个回答

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)
        })
    }
  }
}

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

要在文件 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(arg1, arg2);

看起来是因为你返回的函数( dispatch => {...}) 不是异步函数,所以不能await在里面使用你需要做类似的事情return async dispatch => {...}