我有一个 REST 调用的结果,其中包含文件列表。每个文件都有我必须提取并放置在新数组中的属性。这很简单,并且可以通过一个简单的循环轻松完成。我需要提取的三个属性可以直接访问,而其他三个属性是 HATEOAS 类型,换句话说,这意味着对于结果中的每个文件,我必须进行其他三个异步调用来检索其值。
我的第一直觉是使用 RSVP.all()
来处理我的 promise ,并使用 map< 将新数组中的项目映射到原始文件列表中的相应属性
,但我不知道如何实现这一点。
我想实现如下所示的目标,但我不知道如何获取 itemList
中当前映射项目的索引,以包含 fileList
中的正确文件>。我怎样才能做到这一点?
顺便说一句,如果我以错误的方式使用 RSVP.all()
,我很高兴收到提示!
function createItemList(fileList) {
var promise = new RSVP.Promise(function(resolve, reject) {
var itemList = [];
//For each file in fileList, get the directly accessible properties
//and push it to a new array
for (var i = 0, file; file = fileList[i]; i++) {
currentItem.Name = file.Name;
currentItem.LastModified = new Date(file.TimeLastModified).format("dd-MM-yyyy hh:mm:ss");
currentItem.Version = file.MajorVersion + "." + file.MinorVersion;
itemList.push(currentItem);
}
//This is where it starts to get messy...
//I want to map each item in the new itemlist to the corresponding properties
//in the fileList. If I can include the corresponding file somehow, I could set the
//data in the method 'getModifiedBy' and similar. I believe this should work,
//but I have no idea how I can achieve this.
var modifiedBy = itemList.map(function(item) {
return getModifiedBy(item, fileList[INDEX]);
});
var checkedOutBy = itemList.map(function (item) {
return getCheckedOutBy(item, fileList[INDEX]);
});
var eventDate = itemList.map(function (item) {
return getEventDate(item, fileList[INDEX]);
});
var promises = {
promisesModifiedBy: modifiedBy,
promisesCheckedOutBy: checkedOutBy,
promisesEventDate: eventDate
};
RSVP.all(promises)
.then(function() {
resolve(itemList);
});
});
return promise;
}
最佳答案
在 itemlist
上仅使用一个映射,为您的 3-property-object 返回 Promise。对单个项目使用专用的辅助函数。
顺便说一句,通过new RSVP.Promise
,您正在使用 deferred antipattern虽然绝对没有理由 - RSVP.all()
已经向您返回了结果 promise 。
function createItemList(fileList) {
return RSVP.all(fileList.map(createItem));
}
function createItem(file) {
// get the directly accessible properties
var currentItem = {};
currentItem.Name = file.Name;
currentItem.LastModified = new Date(file.TimeLastModified).format("dd-MM-yyyy hh:mm:ss");
currentItem.Version = file.MajorVersion + "." + file.MinorVersion;
return RSVP.hash({
modifiedBy: getModifiedBy(currentItem, file),
checkedOutBy: getCheckedOutBy(currentItem, file)
eventDate: getEventDate(currentItem, file)
}).then(function(asyncprops) {
// somehow mix the asyncprops with the currentItem
return item; // into a result item
});
}
关于javascript - RSVP.js - 数组上的多个异步函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28218364/