I am using npm memcached package https://www.npmjs.com/package/memcached
It is possible to return data from memcached get method?
Now return data is undefined/
memcached.set('foo', 'bar', 10, function (err) { });
let data1;
memcached.get('foo', function (err, data) {
console.log(data); // bar
data1 = data
});
console.log(data1); // undefined
let data2 = memcached.get('foo', function (err, data) {
console.log(data); // undefined
return data;
});
console.log(data2); // undefined
let data3 = async () => {
let result = await memcached.get('foo', function (err, data) {
console.log(data); // bar
});
console.log(result); // undefined
return result;
}
console.log(data); // {}
2
Answers
You can’t return from get() as it’s an asynchronous callback. What you can do is:
with callbacks:
with promises:
and with async/await:
hope this helps 🙂
Since memcached is async you can’t really return from it, altho I see OP found a way via a promisify wrapper. What you can do is call another function from inside the callback.
Working with async socket communication I’ve had to split up a lot of my workflows into request and receives.
Of course you could always do your work with the data inside the handler too. But in some cases that isnt the best approach.