2 回答

TA貢獻1911條經(jīng)驗 獲得超7個贊
看起來,您想要一個包含每個請求的結(jié)果數(shù)據(jù)的數(shù)組。所以我建議不要將數(shù)據(jù)推送到myRecipes數(shù)據(jù)以返回它。這將自動在列表中“添加”(或更好地替換)它。代碼將如下所示:
async getFavoriteRecipes() {
try {
let myRecipes = []
const response = await this.axios.get("https://david-matan-recipe-api-server.herokuapp.com/api/profiles/myprofile")
let myFavoritedIds = response.data.favoriteRecipe;
myRecipes = await Promise.all(myFavoritedIds.map(async (recipeInfo) => {
if (id.type === "spooncalur") {
const result = await this.axios.get("https://david-matan-recipe-api-server.herokuapp.com/api/recipes/" + recipeInfo.id)
return result.data
} else {
const result = (await this.axios.get("https://david-matan-recipe-api-server.herokuapp.com/api/recipes/userecipe/" + recipeInfo.id))
return result.data
}
}))
this.myFavoriteRecipe = myRecipes
} catch (err) {
if (err.response.status === '401') {
this.$root.store.username = undefined
this.$router.push('/login')
}
console.log(err.response)
}
}
如果您不了解該map功能,這可能會有所幫助https://www.youtube.com/watch?v=DC471a9qrU4或https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array /地圖

TA貢獻1712條經(jīng)驗 獲得超3個贊
Ayk 已經(jīng)解釋了問題的原因......但代碼也可以簡化為
const path = "https://david-matan-recipe-api-server.herokuapp.com/api/recipes/" +
id.type==="spooncalur" ? '' : 'userecipe/'
myRecipes = await Promise.all(myFavoritedIds.map(recipeInfo =>
this.axios.get(path + recipeInfo.id)
))
無需進行this.axios.get(path + recipeInfo.id)異步,因為 Promise 都將一組 Promise 作為參數(shù),而不是結(jié)果值
添加回答
舉報