如何在Ui5中进行多次提取调用



嗨,我想同时调用这些Fetch调用,所以我有平板电脑、智能手机和;显示的笔记本。我该怎么做?我尝试了一些异步函数,但没有成功。

代码:

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")
})
},

您已经让请求同时异步运行。

我假设您希望使用来自所有三个请求的数据设置一次数据模型。在这种情况下,我认为使用Promise.all来组合所有的获取承诺将是一个很好的解决方案。

确保使组合promise的响应变平,以便创建具有<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");
});

最新更新