Return of asynchronous methods javascript

0

I would like to save the return of an asynchronous function. The function is as follows:

cb.tabela(serie).then(function(tabela) {
    console.log(tabela);
}, function(err){
    console.log(err);
});

What I wanted was to be able to do something like:

cb.tabela(serie).then(function(tabela) {
    return tabela;
}, function(err){
    console.log(err);
});

But when I do this I get a Promise {<pending>} . Is there any way to save this return value?

    
asked by anonymous 15.09.2017 / 01:53

1 answer

1

To obtain the return of the promise it is necessary that it be resolved, as below.   So the rule can only be applied after the function callback. For, as an asynchronous function, it does not block the loading of the screen elements.  In your case the rule to mount the table must be in the return of the callback ".then ..".

var tabela = '';
var contador = 0;

var p = function(){
    return new Promise(function(resolve, reject){

       window.setTimeout(
        function() {
          // Cumprimos a promessa !
          resolve('Dados tabela');
        }, Math.random() * 8000 + 1000);
    });
}

p().then(function(result){
   //Adicionar regras
   console.log('Cumprimos a promessa');
   tabela = result;
  
});

setInterval(function(){
    contador++;
    if(contador > 10) return;
    console.log('Contador: ' + contador + ' - Tabela: ' + tabela);
}, 1000);
    
15.09.2017 / 06:04