Reputation: 73044
Take this simple GitHub API request example:
var request = require('request-promise');
var headers = {
'User-Agent': 'YOUR_GITHUB_USERID_HERE'
}
var repos = [
'brandonscript/usergrid-nodejs',
'facebook/react',
'moment/moment',
'nodejs/node',
'lodash/lodash'
]
function requestPromise(options) {
return new Promise((resolve, reject) => {
let json = await request.get(options)
return `${json.full_name} ${json.stargazers_count}`
})
}
(async function() {
for (let repo of repos) {
let options = {
url: 'https://api.github.com/repos/' + repo,
headers: headers,
qs: {}, // or put client_id / client_secret here
json: true
};
let info = await requestPromise(options)
console.log(info)
}
})()
In particular, the line under requestPromise()
where I use await
. When running this in Node.js 7.5.0, I get:
$ node --harmony awaitTest.js
awaitTest.js:51
let json = await request.get(options)
^^^^^^^
SyntaxError: Unexpected identifier
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
If I do it like this, without calling a separate promise, it works:
(async function() {
for (let repo of repos) {
let options = {}
let json = await request.get(options)
let info = json.full_name + ' ' + json.stargazers_count;
console.log(info) // yay!
}
})()
And I can do this the ES5 way:
request.get(options).then(() => resolve(...info...))
But when I call out to a separate promise function, it doesn't work. How can I get that to work?
Upvotes: 1
Views: 2005
Reputation: 1
It seems you are using a Promise constructor where you don't need one
simply set requestPromise as async, and then you can do the following
async function requestPromise(options) {
let json = await request.get(options)
return `${json.full_name} ${json.stargazers_count}`
}
Upvotes: 1