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

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3cdc9-2c356.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3cdc9-2c356.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?