How do I call a function after receiving a value from two callback functions?

Asked 1 years ago, Updated 1 years ago, 105 views


 // ...

var foo, bar

foobar.first(function (value) {
    foo = value
})
foobar.second(function (value) {
    bar = value
})
function next() {
    // ...
}

 // ...

It's a code in this format

I want to call the next() function after the global variable has two callback functions. What should I do?

node.js callback

2022-09-21 19:49

2 Answers

The simplest solution is to check that each variable has been initialized. It runs as a single thread, so there are no synchronization problems such as race conditions.

var foo, bar

foobar.first(function (value) {
    foo = value

    if (foo && bar) { 
      next(); 
    }

})
foobar.second(function (value) {
    bar = value

    if (foo && bar) { 
      next(); 
    }
})

function next() {
    // ...
}

Of course, it is not often used like the above code in practice, and modules such as async.js can solve asynchronous problems relatively easily.

In the long run, we recommend using the advanced method promise.


2022-09-21 19:49

As Jung Dae-won suggested, it would be better to use Promise. If you simply change to Different and Promise of jQuery, I think you can change it as follows. Please keep in mind.

var fooDeferred = $.Deferred();
var barDeferred = $.Deferred();

foobar.first(function (value) {
    fooDeferred.resolve(value);
})
foobar.second(function (value) {
    barDeferred.resolve(value);
})

$.when(fooDeferred.promise(), barDeferred.promise()).done(function(foo,bar) {  
  // If all foo,bar values are passed, then... 
});


2022-09-21 19:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.