【问题标题】:Sync http request in Node [duplicate]在节点中同步 http 请求 [重复]
【发布时间】:2015-07-18 10:37:10
【问题描述】:

我是 node 新手,我正在尝试找出回调及其异步性质。
我有这种功能:

myObj.exampleMethod = function(req, query, profile, next) {
    // sequential instructions
    var greetings = "hello";
    var profile = {};

    var options = {
        headers: {
            'Content-Type': 'application/json',
        },
        host: 'api.github.com',
        path: '/user/profile'
        json: true
    };

    // async block
    https.get(options, function(res) {

        res.on('data', function(d) {
            // just an example
            profile.emails = [
                {value: d[0].email }
            ];
        });

    }).on('error', function(e) {
        console.error(e);
    });

    //sync operations that needs the result of the https call above
    profile['who'] = "that's me"

    // I should't save the profile until the async block is done
    save(profile);

}

鉴于大多数节点开发人员都使用此解决方案或类似解决方案,我还试图了解如何使用 Async library

如何“阻止”(或等待结果)我的脚本流程,直到我从 http 请求中获得结果?可能以异步库为例

谢谢

【问题讨论】:

  • 不,我不这么认为。我的范围在节点中,我想查看此用例中异步库的示例用法
  • "block[ing]" javascript,直到结果返回完全不利于编写异步代码。您需要在异步操作的回调函数中运行您想要在异步操作之后运行的代码。这就是回调函数的全部意义所在。链接的副本很好地解释了这一点。 (下面的答案涵盖了您的特定用例,尽管您实际上并不需要异步库。)

标签: javascript node.js asynchronous node-async


【解决方案1】:

基于您试图“阻止”您的脚本执行这一事实,我认为您对异步的工作原理并没有牢牢把握。你绝对应该阅读我建议的欺骗,尤其是这个回复:

How do I return the response from an asynchronous call?

更具体地回答您的问题:

async.waterfall([
    function(callback) {
        // async block
        https.get(options, function(res) {

            res.on('data', function(d) {
                // just an example
                profile.emails = [
                    {value: d[0].email }
                ];
                callback(null);
            });

        }).on('error', function(e) {
            throw e;
        });
    },
    function(callback) {
        // I should't save the profile until the async block is done
        save(profile);
        callback(null);
    }
]);

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 2014-08-23
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2018-12-31
    • 2018-10-31
    • 2018-02-14
    相关资源
    最近更新 更多