Hola, quiero llamar a estas llamadas Fetch todas juntas al mismo tiempo, por lo que se muestran tabletas, teléfonos inteligentes y computadoras portátiles. ¿Cómo hago esto? Intenté algo con la función asíncrona pero no funcionó.
El código:
onInit: function () { const tabletUrl = '/api/tablets?limit=1000&offset=0'; fetch(tabletUrl).then(res => res.json()).then(res => { const dataModel = new JSONModel(); dataModel.setData({ items: res }); this.getView().setModel(dataModel, "aribadevices") }) const notebookUrl = '/api/notebooks?limit=1000&offset=0'; fetch(notebookUrl).then(res => res.json()).then(res => { const dataModel = new JSONModel(); dataModel.setData({ items: res }); this.getView().setModel(dataModel, "aribadevices") }) const smartphonesUrl = '/api/smartphones?limit=1000&offset=0'; fetch(smartphonesUrl).then(res => res.json()).then(res => { const dataModel = new JSONModel(); dataModel.setData({ items: res }); this.getView().setModel(dataModel, "aribadevices") }) },Ya tiene las solicitudes ejecutándose al mismo tiempo de forma asíncrona.
Supongo que desea configurar el modelo de datos una vez con los datos de las tres solicitudes. En ese caso, creo que usar Promise.all para combinar todas tus promesas de recuperación sería una buena solución.
Asegúrate de aplanar la respuesta de la promesa combinada para crear una sola matriz con <Array>.flat .
const tabletUrl = '/api/tablets?limit=1000&offset=0'; const notebookUrl = '/api/notebooks?limit=1000&offset=0'; const smartphonesUrl = '/api/smartphones?limit=1000&offset=0'; Promise.all([fetch(tabletUrl), fetch(notebookUrl), fetch(smartphonesUrl)]).then(res => Promise.all(res.map(r => r.json()))).then(data => { const dataModel = new JSONModel(); dataModel.setData({ items: data.flat() }); this.getView().setModel(dataModel, "aribadevices"); });