javascript 将 async 和 await 与 export const 一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50804207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using async and await with export const
提问by Marco Jr
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 :)
我无法完成这项工作......它说:await 是一个保留字。是的,当然是......而且我想使用:)
What's wrong ?
怎么了 ?
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)
})
}
}
}
My ReadFromLocalDB is this:
我的 ReadFromLocalDB 是这样的:
export const ReadFromLocalDB = async (key) => {
return AsyncStorage.getItem(key)
}
it's return a promise
这是回报承诺
采纳答案by zero298
return dispatch => {...}needs to also be asyncI believe. Right now, only the top level function is async, not the nested one.
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)
})
}
}
}
回答by Roman
With export and import we are suggested to follow the model:
对于导出和导入,我们建议遵循以下模型:
To define and export a function in the file myFile.js:
要在文件 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);
}
}
To import and apply the function:
导入和应用函数:
import {request} from './myFile'
request(arg1, arg2);
回答by Robert Herhold
It looks like it's because the function you return (dispatch => {...}) is not an async function, so you can't use awaitin it. You would need to do something like return async dispatch => {...}
看起来是因为你返回的函数( dispatch => {...}) 不是异步函数,所以不能await在里面使用。你需要做类似的事情return async dispatch => {...}

