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.
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:
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
.