D
D
doriulbool2018-03-19 17:16:55
JavaScript
doriulbool, 2018-03-19 17:16:55

How to wait for a function to execute and pass its result to a variable?

There is a code - two modules on js, in the first one, sequential execution and filling the variable with the results of adjax requests are written on promises. In the second, I use this function and want to perform one or another action depending on the result. It also failed to write on promises. I ask for your help.

var module1 = (function(){
console.log('Module module1 is initiating');
function _sendsql2server(data){
promise = $.when();
data.sql.forEach(function (v,k){
  promise = promise.then(function(){
  return $.ajax({
    // код удален
  });
  }).then(function(thenResult){
  console.log('Запрос №'+k+' - выполнен');
  data.response.push({"data":thenResult.data,"msg":"Ok"});
  }, function(jqXHR, exception){
  	console.log('Ошибка');
    return $.Deferred();
  });
});
promise.then(function(){
return data;
console.log('Все ok');
});
}
return {_sendsql2server: _sendsql2server};
})();

var checkTableModule = (function (module1) {
$('form').on('submit', function(){
// вырезал код
var _sql= '...'; // Формирую переменую и отправляю ее в функцию
var result = module1._sendsql2server(_sql);
console.log(result);
if(result != ''){
  console.log('Данные присутствуют');
  somefunction1(result);
} else {
  console.log('Данные отсутствуют');
  somefunction2();
}
});
})(module1 || {});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-03-19
@Stalker_RED

You can wait a couple of years:

setTimeout(function(){
  console.log('уф, дождались!')
}, 63072000)

But it’s better not to do this, but to read more about promises until it works out.
In general, the whole approach starting with the words "wait for execution and transfer" is wrong.
Right now you're writing code like this:
1. I'm running aaa()
2. Now I want to run bbb(), but damn aaa() hasn't finished and returned! What to do!? Panic!
And you need to write like this:
1. Let aaa () run, and after it bbb () will run

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question