如何在nodejs同步中进行此请求调用? [英] How can I make this call to request in nodejs synchronous?
问题描述
我的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)
});
承诺运行流程
strong> after get_source_at
返回。
The process
is promised to be run after get_source_at
returns.
这篇关于如何在nodejs同步中进行此请求调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!