【发布时间】:2017-12-16 15:54:35
【问题描述】:
我正试图了解 NodeJS 中的 async/await。
我在一个文件中有一个函数如下:
const getAccessToken = async () => {
return new Promise((resolve, reject) => {
const oauthOptions = {
method: 'POST',
url: oauthUrl,
headers: {
'Authorization': 'Basic ' + oauthToken
},
form: {
grant_type: 'client_credentials'
}
};
request(oauthOptions)
.then((err, httpResponse, body) => {
if (err) {
return reject('ERROR : ' + err);
}
return resolve(body.access_token);
})
.catch((e) => {
reject('getAccessToken ERROR : ' + e);
});
});
};
module.exports = getAccessToken;
此文件在lib 文件夹中另存为twitter.js
在我的index.js 文件中,我有以下内容:
const getAccessToken = require('./lib/twitter');
let accessToken;
try {
accessToken = await getAccessToken();
} catch (e) {
return console.log(e);
}
console.log(accessToken);
我在尝试运行此代码时遇到错误:
> accessKey = await getAccessToken();
> ^^^^^^^^^^^^^^
>
> SyntaxError: Unexpected identifier
> at createScript (vm.js:74:10)
> at Object.runInThisContext (vm.js:116:10)
> at Module._compile (module.js:533:28)
> at Object.Module._extensions..js (module.js:580:10)
> at Module.load (module.js:503:32)
> at tryModuleLoad (module.js:466:12)
> at Function.Module._load (module.js:458:3)
> at Function.Module.runMain (module.js:605:10)
> at startup (bootstrap_node.js:158:16)
> at bootstrap_node.js:575:3
我不能await 所需的功能,因为它被标记为async 吗?
【问题讨论】:
-
什么nodejs版本?
-
8.1.4(在 Ubuntu 上运行)
-
函数
getAccessToken = async () =>不应该是异步的,代码accessKey = await getAccessToken();应该在异步函数中 -
如果我在
const getAccessToken = require('./lib/twitter').getAccessToken;下方添加console.log(getAccessToken);,它会输出[AsyncFunction: getAccessToken],这表明它是什么? -
好吧,我想我明白你现在所说的了。我会做一些调查,但感谢您的帮助@Naeem
标签: javascript node.js asynchronous async-await