Tengo dos puntos finales diferentes en el proyecto en el que estoy trabajando. Uno de estos puntos finales (categorías) me da el nombre de categoría y el valor de identificación, y el otro (productos) me da solo el valor de identificación de categoría. Quiero extraer los valores de identificación de ambos puntos finales y agregar el nombre correspondiente al valor de identificación de la parte de categoría de los campos con valores de identificación iguales a la parte del producto.
Realicé sincronizaciones usando el bucle for a continuación y luego lo sincronicé con el nombre de Categoría del producto, pero había demasiado código y no funciona de manera estable. Por estable me refiero a que a veces llega el dato ya veces no, tampoco da ningún error. ¿Cómo crees que puedo escribir más corto y más estable?
datos:
products: { items: [{ categoryName: '' }], }, cretated(){ fetch('example/products') .then((response) => { return response.json(); }) .then((data) => { this.products = data; }); fetch('example/categories') .then((response) => { return response.json(); }) .then((data) => { this.categories = data; this.pushNametoCategoryNames(); }); } methods() { pushNametoCategoryNames() { for (let i = 0; i < this.products.items.length; i++) { for (let j = 0; j < this.categories.length; j++) { console.log(this.products); console.log(this.categories[j]); if (this.products.items[i].categoryId == this.categories[j].id) { this.products.items[i].categoryName = this.categories[j].name; } } } }, }Nunca puede garantizar que this.pushNametoCategoryNames() se ejecutará then de las dos llamadas de fetch , a menos que llame a la segunda fetch desde la primera fetch , o use async-await .
fetch('example/products') .then((response) => { return response.json(); }) .then((data) => { this.products = data; fetch('example/categories') .then((response) => { return response.json(); }) .then((data) => { this.categories = data; this.pushNametoCategoryNames(); }); }); async cretated(){ this.products = await (await fetch('example/products')).json(); this.categories = await (await fetch('example/categories')).json(); this.pushNametoCategoryNames(); }Promise.all ) cretated(){ Promise.all([fetch('example/products'), fetch('example/categories')]).then(values => { Promise.all([values[0].json(), values[1].json()]).then(data => { this.products = data[0]; this.categories = data[1]; this.pushNametoCategoryNames(); }); }); this.pushNametoCategoryNames(); }Puede usar el map y esperar respuestas:
new Vue({ el: "#demo", data() { return { products: [], categories: [] } }, async mounted(){ await fetch('https://jsonplaceholder.typicode.com/posts/') .then((response) => { return response.json(); }) .then((data) => { this.products = data; }); await fetch('https://jsonplaceholder.typicode.com/users/') .then((response) => { return response.json(); }) .then((data) => { this.categories = data; }); this.pushNametoCategoryNames(); }, methods: { pushNametoCategoryNames() { this.products = this.products.map(p => { const cat = this.categories.find(c => p.userId === c.id).username cat ? p.CATNAME = cat : p.CATNAME = 'EMPTY' return { ...p } }) } } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="demo"> {{products}} </div>