D
D
Dmitry Shidlovsky2016-04-26 13:39:03
Node.js
Dmitry Shidlovsky, 2016-04-26 13:39:03

How to return a value in node.js from a function inside which asynchronous functions are used?

We have the redis_key key in the radish database with the value 2016-02-02 23:59:59+00:00

var Redis = require('ioredis');
redis = new Redis();

var default = '2016-01-01 00:00:00+00:00';

function getLastTime() {
  var last = default;
        redis.get('redis_key', function (err, result) {
           last = result;
        });
  return last;
}

console.log(getLastTime()); // 2016-01-01 00:00:00+00:00
// а хотелось бы видеть 2016-02-02 23:59:59+00:00 полученный из редиса.

I tried to use https://github.com/ybogdanov/node-sync but it is not suitable for returning a value from a function.
Important! It is necessary that the function return a value that is calculated using asynchronous functions.
ps. I understand that the above example can be rewritten to the ideology of asynchronous programming, but the code is given as a simplified example.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Shidlovsky, 2016-04-29
@warwar_dp

It looks like there are no options.
Just write your own structure that stores the necessary data, use this data in synchronous functions, and update the data using asynchronous functions periodically.
Simplified example.

const Redis = require('ioredis');
redis = new Redis();

var default_time = '2016-01-01 00:00:00+00:00';

function getLastTime() {
  return default_time;
}

setInterval(function() {
  redis.get('redis_key', function (err, result) {
    if (err === null) {
      default_time = result;
    }
  });
}, 100);

console.log(getLastTime());

T
Timur Shemsedinov, 2016-04-26
@MarcusAurelius

Through callbacks

function getLastTime(callback) {
  var last = default;
  redis.get('redis_key', function (err, result) {
    callback(result);
  });
}
// Usage:
getLastTime(function(last) {
  console.log(last);
});

I
Ivan Bogachev, 2016-04-26
@sfi0zy

This question is not only about nodejs - there is an approach to solving the issue of returning a value from an asynchronous function using callbacks.

C
catHD, 2016-04-29
@catHD

This is the core of node js callback/promise basics.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question