V
V
Vitaly Stolyarov2016-06-05 23:02:55
JavaScript
Vitaly Stolyarov, 2016-06-05 23:02:55

How to "soften" the impact of callbacks in JS?

There are no particular difficulties in asynchronous programming and programming in JS, but as the project grows, it becomes necessary to execute several asynchronous requests within the same context at once (especially relevant for Node.js), and it happens that already on the third nesting, brackets and everything else to anonymous callbacks start to be an eyesore.
For example:

do.smth1(function(arg1){
    
  ////code
  ////code
  ////code
 
 
  do.smth2(function(arg2){
      
    ////code
    ////code
    ////code
      
    do.smth3(function(arg3){
      
      ////code
      ////code
      ////code

    });

   });

});

The main task is to execute asynchronous requests sequentially, but with such attachments, the code becomes difficult to read. What are the options for structuring things like this in Node.js?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Konstantin Kitmanov, 2016-06-06
@Ni55aN

  1. Avoid anonymous functions anyway, named functions are easier to refactor and debug.
    If the last two points for some reason do not fit - the good old async .

S
Sergey, 2016-06-05
Protko @Fesor

https://habrahabr.ru/post/282477/ + promises

A
Alexander Taratin, 2016-06-06
@Taraflex

It 's strange that no one has suggested
https://learn.javascript.ru/generator#library-co
https://www.npmjs.com/package/co
" functions via yield fun(...)

S
Sergey Volkov, 2016-06-05
@format1981

Promises or make a separate function/method for each callback.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question