Ich versuche, mich in NodeJS async/erwarten.Anforderung einer asynchronen Funktion in NodeJS
Ich habe eine Funktion in einer Datei wie folgt:
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;
Diese Datei als twitter.js
in einem lib
Ordner
In meiner index.js
Datei gespeichert habe ich folgendes:
const getAccessToken = require('./lib/twitter');
let accessToken;
try {
accessToken = await getAccessToken();
} catch (e) {
return console.log(e);
}
console.log(accessToken);
Ich erhalte eine Fehlermeldung, wenn ich versuche, den folgenden Code auszuführen:
> 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
Kann ich nicht await
die erforderliche Funktion, wie es markiert ist async
?
Welche Version von NodeJs? –
8.1.4 (unter Ubuntu) –
die Funktion 'getAccessToken = async() =>' sollte nicht async sein, und der Code 'accessKey = wartet auf getAccessToken();' sollte innerhalb einer asynchronen Funktion sein –