Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

javascript - Any workaround for this method without convert snapshotChanges() into promise?

I want to return cartIdFire but it returns undefined because snapshot method is return observable
so, there is any workaround for returning cartIdFire without convert snapshot method into promise ?

private async getServer() 
{
   this.db.list('/shopping-carts/').snapshotChanges()
   .subscribe(x => this.cartIdFire = x);
   return cartIdFire;
 }   
private async getOrCreateCartId() //to create a cartid or acceess the cartid
  
  {
    let cartId = localStorage.getItem('cartId'); //to create a cartid or acceess 
    if(cartId) 
    {
      return cartId;
    }
     this.id = await this.getServer();
     console.log(this.id);
     console.log(this.cartIdFire); //it gives undefined
    if(this.cartIdFire)
    {
       localStorage.setItem('cartId' ,result.key);
       return this.cartIdFire;
    } 
      let result =  await this.create(); 
      localStorage.setItem('cartId' ,result.key);
      return  result.key;
  }

so i can't return subscriber from getServer() method. Because i have to save
the cartFireId in the local storage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In this scenario, await this.getServer() will not work, it will not wait to be solved, it only works in Promise, not in Observable, where it is solved within the subscribe

A simple solution would be, in the getServer() method to convert the Observable to Promise, using toPromise() and returning this value

private async getServer() 
{
   return this.db.list('/shopping-carts/').snapshotChanges().toPromise()
}

And get the cartIdFire in the getOrCreateCartId() method

this.cardIdFire = await this.getServer()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...