【问题标题】:request-promise throwing Unexpected identifier error when using awaitrequest-promise 在使用 await 时抛出 Unexpected identifier 错误
【发布时间】:2017-06-25 13:57:16
【问题描述】:

以这个简单的 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',
    '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() 下的行,我使用await。在 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 函数时,它不起作用。我怎样才能让它发挥作用?

【问题讨论】:

  • 您需要意识到await 仅在声明为async 的函数中才有意义...
  • 我也尝试过这样声明——async function requestPromise(options) { ...
  • await 用于新 Promise 的回调中,所以...但requestPromise 存在更大的问题...承诺永远不会解决或拒绝
  • 嗯,好点子 - 试图理清新语法如何共存令人困惑;)
  • async/await 是异步编码的倒退……如果你更喜欢函数式编码而不是命令式编码:p

标签: javascript node.js asynchronous async-await ecmascript-2017


【解决方案1】:

您似乎正在使用不需要的 Promise 构造函数

只需将requestPromise设置为async,就可以进行如下操作

async function requestPromise(options) {
    let json = await request.get(options)
    return `${json.full_name} ${json.stargazers_count}`
}

【讨论】:

  • 做得很好——这更有意义。谢谢!
猜你喜欢
  • 2021-07-22
  • 2023-03-24
  • 2016-12-08
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
相关资源
最近更新 更多