2 回答
TA贡献1911条经验 获得超7个赞
看起来,您想要一个包含每个请求的结果数据的数组。所以我建议不要将数据推送到myRecipes数据以返回它。这将自动在列表中“添加”(或更好地替换)它。代码将如下所示:
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条经验 获得超3个赞
Ayk 已经解释了问题的原因......但代码也可以简化为
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 作为参数,而不是结果值
添加回答
举报