如何在 nodejs 中同步请求这个调用? [英] How can I make this call to request in nodejs synchronous?

查看:28
本文介绍了如何在 nodejs 中同步请求这个调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 nodejs 应用程序中有一个名为 get_source_at 的函数.它以 uri 作为参数,其目的是从该 uri 返回源代码.我的问题是我不知道如何让函数同步调用请求,而不是给它那个回调函数.我希望控制流在加载 uri 所需的几秒钟内停止.我怎样才能做到这一点?

I have a function in my nodejs application called get_source_at. It takes a uri as an argument and its purpose is to return the source code from that uri. My problem is that I don't know how to make the function synchronously call request, rather than giving it that callback function. I want control flow to halt for the few seconds it takes to load the uri. How can I achieve this?

function get_source_at(uri){
    var source;
    request({ uri:uri}, function (error, response, body) {
        console.log(body);
    });
    return source;
}

此外,我已经阅读了有关事件"以及节点如何事件化"的内容,我在编写代码时应该尊重这一点.我很高兴这样做,但在继续我的应用程序的控制流之前,我必须有一种方法来确保我拥有来自 uri 的源代码 - 所以如果这不是通过使函数同步,如何做到?

Also, I've read about 'events' and how node is 'evented' and I should respect that in writing my code. I'm happy to do that, but I have to have a way to make sure I have the source code from a uri before continuing the control flow of my application - so if that's not by making the function synchronous, how can it be done?

推荐答案

你应该避免同步请求.如果你想要同步控制流之类的东西,你可以使用 async.

You should avoid synchronous requests. If you want something like synchronous control flow, you can use async.

async.waterfall([
    function(callback){
        data = get_source_at(uri);
        callback(null, data);
    },
    function(data,callback){
        process(data, callback);
    },
], function (err,result) {
    console.log(result)
});

process 承诺在 get_source_at 返回后运行.

The process is promised to be run after get_source_at returns.

这篇关于如何在 nodejs 中同步请求这个调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆