Answer the question
In order to leave comments, you need to log in
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 полученный из редиса.
Answer the question
In order to leave comments, you need to log in
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());
Through callbacks
function getLastTime(callback) {
var last = default;
redis.get('redis_key', function (err, result) {
callback(result);
});
}
// Usage:
getLastTime(function(last) {
console.log(last);
});
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question