I am writing a website socket server on nodejs, using redis, in particular of the same name lib. So, when I retrieve the answer, the script execution goes on without waiting for the callback call with the result. In a browser, I could use $ .Deferred. And what to do in nodejs?

Here is an example code for clarity:

console.log("STEP 1"); // ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° сСссии Π½Π° сущСствованиС rc.exists("session:" + sid, function(err, res) { if (!res) { console.log((new Date()) + " Session not exists in db"); request.reject(401, "Authentication required"); } console.log("STEP 2"); }); console.log("STEP 3"); 

So the STEP 2 call comes last, but you need to do it in order.

  • async - Yura Ivanov
  • @Yura_Ivanov well, can we back up with a piece of code? - ReklatsMasters

1 answer 1

There are too many different methods in async , for the given question it is difficult for the code to choose something specific. maybe it's a series, maybe a waterfall or parallel. See the description. One of the options:

 async.series([ function(cb){ console.log('1'); cb(null,1);// ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ - ошибка, Ссли Π½Π΅ null, Ρ‚ΠΎ сСрия прСрвСтся }, function(cb){ rc.exists("session:" + sid, function(err,res){ console.log('2'); cb(err,res); }); }, function(cb){ console.log('3'); cb(null,3); }], // эта функция Π±ΡƒΠ΄Π΅Ρ‚ Π²Ρ‹Π·Π²Π°Π½Π°, ΠΊΠΎΠ³Π΄Π° Π²Ρ‹ΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ сСрий закончится function(err, results){ // Π°Π½Π°Π»ΠΈΠ· ошибки, возникшСй Π½Π° ΠΊΠ°ΠΊΠΎΠΌ-Π»ΠΈΠ±ΠΎ этапС if (err) ... console.log(results);// здСсь Π±ΡƒΠ΄Π΅Ρ‚ массив ΠΈΠ· Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π΅Π½Π½Ρ‹Ρ… Π·Π½Π°Ρ‡Π΅Π½ΠΈΠΉ // Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ ΠΈΠ· коллбэков (Π²Ρ‚ΠΎΡ€ΠΎΠΉ ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ cb) } );