V
V
vasromand2015-01-31 22:23:21
Node.js
vasromand, 2015-01-31 22:23:21

How to write asynchronous code correctly?

Hello!
I'm trying to figure out how to write asynchronous code (node.js) correctly, there is a problem with one construct. Let's say there is a certain function that receives data, changes it under a certain condition and passes it on. How to properly call callback?

function(data, callback){
  if(data.someCondition){
    doAsyncCode(data, function(err, result){
      // Здесь по идее должен быть вызов callback
      callback(data)
      return
    }
  }
  // Но и здесь должен быть вызов callback, но без модификации данных
  callback(data)
}

Whether so I described implementation - through double callback? Or does everything need to be written differently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
index0h, 2015-02-01
@vasromand

1. Your callback will be executed 2 times, if it is so planned - everything is correct, otherwise - no. The second callback must be in else.
2. return is not needed because nothing happens after it anyway.
Other than that, I don't see any obvious problems.

Y
Yuri Shikanov, 2015-01-31
@dizballanze

You got it right, that's how it should be done. Only if is missing return.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question