Javascript 使用WAIT时请求承诺引发意外标识符错误
以这个简单的GitHub API请求为例:Javascript 使用WAIT时请求承诺引发意外标识符错误,javascript,node.js,asynchronous,async-await,ecmascript-2017,Javascript,Node.js,Asynchronous,Async Await,Ecmascript 2017,以这个简单的GitHub API请求为例: var request = require('request-promise'); var headers = { 'User-Agent': 'YOUR_GITHUB_USERID_HERE' } var repos = [ 'brandonscript/usergrid-nodejs', 'facebook/react', 'moment/moment', 'nodejs/node', 'loda
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)
}
})()
特别是,requestPromise()
下我使用的wait
行。在Node.js 7.5.0中运行此功能时,我得到:
$ 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
如果我这样做,不要求单独的承诺,它会起作用:
(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!
}
})()
我可以通过ES5的方式做到这一点:
request.get(options).then(() => resolve(...info...))
但是当我调用一个单独的promise函数时,它不起作用。我怎样才能让它工作呢?似乎您正在使用一个不需要的承诺构造函数 只需将requestPromise设置为async,然后就可以执行以下操作
async function requestPromise(options) {
let json = await request.get(options)
return `${json.full_name} ${json.stargazers_count}`
}
您需要意识到,
await
仅在声明为async
的函数中有意义。我也尝试过声明它-async函数requestPromise(选项){…
await是在对新承诺的回调中使用的,所以…但是,requestPromise
有一个更大的问题…承诺永远不会得到解决或改变,嗯,很好的一点-尝试整理新语法是如何共存的是令人困惑的;async/await
是异步编码的一个倒退…如果你喜欢fu的话NCONAL过度命令式编码:pNicely done-这更有意义。谢谢!