我有一个REST调用的结果,该调用包含一个文件列表。每个文件都有我必须提取并放置在一个新数组中的属性。这很简单,很容易用一个简单的循环来完成。我需要提取的三个属性可以直接访问,而另外三个属性是HATEOAS类型的,换句话说,对于结果中的每个文件,我必须进行另外三个异步调用才能检索它的值。
我的第一反应是使用RSVP.all()处理我的承诺,并使用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;
}发布于 2015-01-29 17:39:56
仅在itemlist上使用一个映射,该映射将返回对您的3个属性对象的承诺。对单个项使用专用的辅助函数。
顺便说一句,在使用new RSVP.Promise时,您使用的是deferred antipattern,而绝对没有任何理由-- RSVP.all()已经将结果承诺返回给您。
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
});
}https://stackoverflow.com/questions/28218364
复制相似问题