skip to Main Content

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


  1. You can’t return from get() as it’s an asynchronous callback. What you can do is:

    with callbacks:

    memcached.get('foo',(err, data) => {
      if(err) {
        console.log('error: ', err);
      } else {
        console.log('data: ', data);
      }
    });
    

    with promises:

    memcached.get('foo')
        .then((data) => {
            console.log('data: ', data);
        })
        .catch((err) => {
            console.log('error: ', err);
        });
    

    and with async/await:

    const getData = async () => {
        try {
            const data = await memcached.get('foo');
            console.log('data: ', data);
        } catch (err) {
            console.log('error: ', err);
        }
    }
    

    hope this helps 🙂

    Login or Signup to reply.
  2. 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.

    
    memcached.get('foo',(err, data) => {
      doStuff(data);
    });
    
    function doStuff(data) {
    //do some stuff here
    }
    

    Of course you could always do your work with the data inside the handler too. But in some cases that isnt the best approach.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search