【问题标题】:Using async and await with export const将 async 和 await 与 export const 一起使用
【发布时间】:2018-11-21 02:04:24
【问题描述】:

我无法完成这项工作……上面写着: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)
}

它返回一个承诺

【问题讨论】:

  • 从'export const'更改它(即使用'let');这与问题/问题有关吗?如果没有,请将其从标题中删除。请记住消除不相关的信息并缩小问题范围。
  • return dispatch => {...} 也必须是 async 我相信。现在,只有顶层函数是异步的,而不是嵌套的。

标签: javascript reactjs react-native


【解决方案1】:

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

【讨论】:

  • 谢谢,零!是的,你是对的 !就是这个原因!
【解决方案2】:

导出和导入我们建议遵循模型:

在文件 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);

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 完全正确——仅仅因为内部函数位于 async 函数中并不意味着您可以在其中使用 await。函数await被使用,它本身必须是async
    猜你喜欢
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 2019-04-15
    • 2014-06-19
    • 2018-01-14
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多