The problem of passing values between javascript functions?

question: the ajax request initiated within a function will get a code, so as a b function, how to get the return value (code) of a function? The b function is triggered by other events.


var ajaxCode;
function a() {
    ajax({
        success: function(data){
            ajaxCode = data.code;
        }
    })
}

function b(){
    console.log(ajaxCode);
}

$('button').trigger('EventName',b);

this question should have been finished a long time ago. There are only three common ways of implementation:

  1. use the traditional callback function callback
  2. use Promise
  3. use the event mechanism trigger on

I'm not familiar with the RxJs mentioned by others. At first glance, class Promise, is a good way to synchronize asynchronous programming.


function a( callBack ){
    $.ajax({ 
        url: "xxxxxxx",  
        success: function(data){
           if(data){
               return callBack&& callBack(data)
           }
        }
    })
}

function b(){
    a(function(data){
        //b
    })
}

this ensures that when the b event is triggered, the value of an is Synchronize. It's not going to happen that if you don't get the value of a, you have to do what b wants to do.


use promise

function a(){
  return ajax({...})
}

function b(){
  a().then(res=>{
    // res 
  })
}

it's OK to write on the second floor, and the one on the first floor can only be used for Synchronize, otherwise


use rxjs


rxjs is very suitable for such a scenario. Learn about

.
Menu