请求 - 承诺在使用等待

时间:2017-02-08 04:37:17

标签: 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',
    '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()的{​​{1}}下的行。在Node.js 7.5.0中运行时,我得到:

await

如果我这样做,没有单独的承诺,它就有效:

$ 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

我可以用ES5方式做到这一点:

(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!
    }
})()

但是当我呼唤一个单独的诺言功能时,它并没有起作用。我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

您似乎正在使用Promise构造函数,而您不需要一个

只需将requestPromise设置为async,然后就可以执行以下操作

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