简体   繁体   English

nodejs 异步库和 redis

[英]nodejs async library and redis

After a long time of "no.. I don'*t want to do this.." I finally need to use the async.js library.经过长时间的“不..我不想这样做..”我终于需要使用 async.js 库。

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 );

      }

    });

}

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 );

      }

    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM