简体   繁体   中英

How to make sync function from async in node.js?

I've a return type function:

var responseData = '';
function getResponseFromKey(key){

    client.get(key, function(err, reply){
        responseData = reply;
    });
    return responseData;
}

When I call this function first time it returns blank and then second time returns my value what I want after running again.

I'm calling this function to print in html page.

http.createServer(function(request, response){
    response.writeHead(200, {'Content-Type':'text/plain'});
    getResponseFromKey("my_key");   
    console.log(responseData);
}).listen(8083);

As I'm familiar with node the function is going in asynchronous way. Can you please help me to make synchronous way? Do I need to use generators in that case?

Help would be appreciated!

You can use callback , promise or generator .

Using callback, you need to send a callback function and call it instead of returning a value

function getResponseFromKey(key, callback){
  client.get(key, function(err, reply){
    callback(reply);   
  });
}

http.createServer(function(request, response){
  response.writeHead(200, {'Content-Type':'text/plain'});
  getResponseFromKey("my_key", function() {
    console.log(responseData);
  });   
}).listen(8083);

Using promise, you need to return a Promise

function getResponseFromKey(key) {
  return new Promise(function(resolve, reject) {
    client.get(key, function(err, reply) {
      return resolve(reply);   
    });
  })
}

http.createServer(function(request, response){
  response.writeHead(200, {'Content-Type':'text/plain'});
  getResponseFromKey("my_key").then(function(responseData) {
    console.log(responseData);
  });   
}).listen(8083);

If you are using and up-to-date version of nodejs, you can use arrow functions, to make your code more readable.

Your client.get function is async try returing return responseData; inside the client.get body

var responseData = '';
 function getResponseFromKey(key ,cb){

 client.get(key, function(err, reply){
    responseData = reply;
    return cb(responseData);
 });

}

http.createServer(function(request, response){
 response.writeHead(200, {'Content-Type':'text/plain'});
 getResponseFromKey("my_key", function(responseData) {
  console.log(responseData);
});   
}).listen(8083);

In many case, the callback is not a good choose.

You can use async , promises , generators and async functions which supported in es7 .

I recommend promises beacuse the promise a key features in ES6.

I think this article will help you.

https://blog.risingstack.com/node-js-async-best-practices-avoiding-callback-hell-node-js-at-scale/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM