Alamcenar variable from a promise

0

I have the following fragment that what it does is store the object obtained in response to the promise in the variable objectNew .then (res = > .....

var objetoNew ={};
firebaseService.tiendas().then(res=>{
  console.log('method1', res);
  objetoNew = res;
})
console.log(objetoNew);

when I do the console.log within the then, if I get the data, but when making the object console out of the promise this variable is still empty, That is, I am not overwriting the global variable (New object) from the then.

Thank you very much friends!

    
asked by Diego Monsalve 04.11.2018 в 23:11
source

2 answers

0

Good morning, colleague, it would be good if you please put the whole code in order to have more reference of what could be happening but at first glance it seems that your problem is that you are losing the scope of the result when the call is resolved. Try this and tell me:

var newObject = {};
newObject = firebaseService.tiendas().then( res => {
return res;
});
console.log(objetoNew);
    
answered by 05.11.2018 в 20:31
0

You have two ways to control the flow.

A) Wrapping all the code in the first promise:

var objetoNew ={};
firebaseService.tiendas().then(res=>{
  console.log('method1', res);
  objetoNew = res;
  return res;
}).then((res) => { // esto es redundante porque ya tienes la global objetoNew

  // haces cosas con objetoNew
});

B) Using async / await

Since await can only be used within a function async you would have to encapsulate all the logic in a function. Something like:

async function logicaDeObjetoNew() {
   var objetoNew = await firebaseService.tiendas();
   console.log(objetoNew);

   // haces cosas con objetoNew
}

logicaDeObjetoNew();
    
answered by 06.11.2018 в 00:39