-1

After a long time of "no.. I don'*t want to do this.." I finally need to use the async.js library.

I have no glue how to use it in a way it will make me happy...

Let's consider this pseudo function which is very simplified:

Seriosly.. I don't even know how to start.. ANY kind of help would be good help.^^

getOPGdata( socket, [ 'url1', 'url2', 'url3', 'url3' ], 'requestid-5364356' );

function getOPGdata( socket, urls, id ){

  var results = {};
  results[id] = [];

  urls.forEach( function( url ) {

    url = trim( url );

    redis.hgetall( 'ogp:'+url, function ( err, reply ) {

      if( reply ) { 

        results[id].push( reply );

      } 

      else {

        results[id].push( refreshOPGcache( url ) );

      }

    });

  });

  socket.emit('ogp', results );

}

refreshOPGcache( url ){

  redis.hgetall( 'cache:'+url, function ( err, reply ) {

    return reply;

  }

}

Edit:

is this the right way to do it?

function getOPGdata( socket, urls, id ){


  var results = {};
  results[id] = [];

  async.map( urls, getOGPfromCache, function(err, r){

    results[id] = r;
    console.log( results );

  });

}

function getOGPfromCache( url, callback ){

    redis.hgetall( 'ogp:'+url, function ( err, reply ) {

      if( err ){ callback( null, false ); }

      if( reply ) { 

        callback( null, reply );

      } 

      else {

        getFreshOPGdata( url, callback );

      }

    });

}

function getFreshOPGdata( url, callback ){

    redis.hgetall( 'justademo:'+url, function ( err, reply ) {

      if( err ){ callback( null, false ); }

      if( reply ) { 

        callback( null, reply );

      } 

      else {

        callback( null, false );

      }

    });

}
user2429266
  • 390
  • 1
  • 3
  • 19
  • You need to learn about javascript closures. [See this answer](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) for a far more comprehensive answer than I'm willing to write out at the moment. Once you grasp that, the async stuff is fairly straight forward. – Jason Apr 17 '14 at 13:27

1 Answers1

0

I confirm this as a working solution.

function getOPGdata( socket, urls, id ){


  var results = {};
  results[id] = [];

  async.map( urls, getOGPfromCache, function(err, r){

    results[id] = r;
    console.log( results );

  });

}

function getOGPfromCache( url, callback ){

    redis.hgetall( 'ogp:'+url, function ( err, reply ) {

      if( err ){ callback( null, false ); }

      if( reply ) { 

        callback( null, reply );

      } 

      else {

        getFreshOPGdata( url, callback );

      }

    });

}

function getFreshOPGdata( url, callback ){

    redis.hgetall( 'justademo:'+url, function ( err, reply ) {

      if( err ){ callback( null, false ); }

      if( reply ) { 

        callback( null, reply );

      } 

      else {

        callback( null, false );

      }

    });

}
user2429266
  • 390
  • 1
  • 3
  • 19