Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this call to request in nodejs synchronous?

Tags:

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; } 

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?

like image 229
Trindaz Avatar asked Mar 27 '12 06:03

Trindaz


People also ask

How do you call a synchronous API?

To make it work, you need to wrap it inside an async function! This is how you do it: const request = async () => { const response = await fetch('https://api.com/values/1'); const json = await response.

How do you call asynchronous in node JS?

The asynchronous function can be written in Node. js using 'async' preceding the function name. The asynchronous function returns implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event-loop.


2 Answers

You can with deasync:

function get_source_at(uri){     var source;     request({ uri:uri}, function (error, response, body) {         source = body;         console.log(body);     });     while(source === undefined) {       require('deasync').runLoopOnce();     }     return source; } 
like image 171
abbr Avatar answered Sep 22 '22 22:09

abbr


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) }); 

The process is promised to be run after get_source_at returns.

like image 41
Lai Yu-Hsuan Avatar answered Sep 25 '22 22:09

Lai Yu-Hsuan