Return of javascript asynchronous methods

Asked

Viewed 340 times

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);
});

I wish I could do something like:

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

but when I do I get one Promise {<pending>}. Is there any way to save that return value?

  • The idea of working with asynchronous methods is precisely that there are no "stopped" code snippets, waiting for the resolution of slower snippets as external calls (the Fetch API is a good example). In this case, instead of returning table, you should call the function that needs it to continue, such as "montaTable(table);"...

  • You have to "save that return" where you have it console.log(tabela);. Is there a problem putting that code there? , or a function call that passes tabela);?. You could use async/await, but if it’s too little, it might be simpler.

  • Nunk.lol I tried to do this, to call a function to manipulate the data but I can’t access it, when I try to do this I get Promise {<pending too>}

1 answer

1

To obtain the return of the Promise it is necessary that the same is resolved, as below. Thus the rule can only be applied after the callback of the function. Because, as an asynchronous function, it does not block the loading of screen elements. In your case the rule for mounting the table should be in callback return ". 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);

  • then @Leandro, in this case my function cb.table(serie) is already the Promise. The way you talk instead of me doing New Promise as you suggested, I did Re-turn cb, Flat (series), but still did not succeed.

  • @roooooon actually new Promise I used only to simulate your situation, where I did p() is the same as your cb.table(serie) what I suggested is to apply your rules after return in function then

Browser other questions tagged

You are not signed in. Login or sign up in order to post.