Javascript RSVP.js-阵列上的多个异步函数调用
我有一个包含文件列表的REST调用的结果。每个文件都有我必须提取并放入新数组中的属性。这很简单,并且可以通过一个简单的循环轻松完成。我需要提取的三个属性可以直接访问,而另外三个属性是HATEOAS类型的,换句话说,对于结果中的每个文件,我必须进行另外三个异步调用来检索它的值 我的第一反应是使用Javascript RSVP.js-阵列上的多个异步函数调用,javascript,arrays,asynchronous,promise,rsvp.js,Javascript,Arrays,Asynchronous,Promise,Rsvp.js,我有一个包含文件列表的REST调用的结果。每个文件都有我必须提取并放入新数组中的属性。这很简单,并且可以通过一个简单的循环轻松完成。我需要提取的三个属性可以直接访问,而另外三个属性是HATEOAS类型的,换句话说,对于结果中的每个文件,我必须进行另外三个异步调用来检索它的值 我的第一反应是使用RSVP.all()处理我的承诺,并使用map将新数组中的项映射到原始文件列表中的相应属性,但我不知道如何实现这一点 我想实现以下目标,但我不知道如何在itemList中获取当前映射项的索引,以包含file
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;
}
在
itemlist
上仅使用一个映射,该映射将返回对3-property-object的承诺。对单个项目使用专用的辅助功能
顺便说一句,使用new RSVP.Promise
您正在使用,但绝对没有理由-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
});
}
这正是我希望它的工作方式,尽管如此,我很难真正理解正在发生的事情,即使是在调试时!我想我得仔细阅读一下承诺。另外,感谢您指出延迟反模式的用法!我一点也不知道!