将 async 和 await 与 export const 一起使用 [英] Using async and await with export const

查看:41
本文介绍了将 async 和 await 与 export const 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't make this work...it's says: await is a reserved word. Yes, of course it is...and I'd like to use it :)

怎么了?

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 函数如下所示:

My ReadFromLocalDB function looks like this:

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

它返回一个承诺

推荐答案

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

return dispatch => {...} needs to also be async I believe. Right now, only the top level function is async, not the nested one.

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

这篇关于将 async 和 await 与 export const 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆