简体   繁体   中英

How to wait for typescript / javascript promise before returning value

This is my first post so I hope I do it right. This is my first exposure to promises and 3 hours in I still can't get it. Our project does not have support for Async Wait, unfortunately. I'm using pouchdb over sqlite.

this.recipes is used to display a page of recipes. It returns as empty, however the first time, and then always lags one recipe behind after each recipe is added. I am pretty sure this is because I return this.recipeBook before all the promises are completed. I realize in the code I posted the final return is dangling outside of any promise, but when I put it in a promise I get a "type void is not assignable to type any[]" error in my RecipesPage.ts.

I appreciate any support you guys can offer and am excited to learn the right way to hand this, and thank you in advance.

This is my call in RecipesPage.ts:

this.recipes = this.database.getAllRecipes();

This is the method in database.service.ts:

public getAllRecipes() {
this.recipeBook = new Array<Recipe>();

this.recipeDatabase.allDocs
({
  include_docs: true,
}).then(docs => {
  this.objectArray = docs.rows.map(row => {
    return row.doc;
  })
}).then(function (){
  for (let object of this.objectArray) {
    this.myRecipe = this.convertObjectToRecipe(object);
    this.recipeBook.push(this.myRecipe);
  }
})
return this.recipeBook;
}

You don't. There's no real way to 'unpack' a promise like this. The closest you can realistically get is polling.

Instead, return the promise and call .then on the promise where you're waiting for it. This is ultimately what async and await are doing under the hood. Make decisions in the UI to choose how to render your content before its loaded (and as its being loaded).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM