承诺的循环.如何检测哪个promise现在返回结果
Loop of promises. How to detect which promise returns the result now?
我认为这是一个普遍的问题,但具体情况是:
我使用猛犸模块将docx
文件转换为html
。模块返回一个promise
。
我有一个文件数组,当我使用循环为每个文件创建一个promise时,我需要知道哪个promise返回给我一个结果(以知道哪个文件被处理了)。
for(var i=0;i<filesPaths.length;i++){
mammoth.convertToHtml( {path: filesPaths[i]} )
.then(function(result){
filesHtml.push(result.value);
//here I need to know the value of filesPaths[i]
})
}
在写这个问题的时候,答案变得显而易见了(通常是这样:))。
你可以用一个自调用的函数来包装承诺,并将相关信息存储在局部变量中。
for(var i=0;i<filesPaths.length;i++){
(function(){
var fileName = filesPaths[i]; //or any other information related to promise
mammoth.convertToHtml( {path: filesPaths[i]} )
.then(function(result){
filesHtml.push({
text:result.value,
fileName:fileName
});
})
})()
}
您可以使用.map()数组方法(在函数调用方面与您的解决方案非常相似,但更简洁):
filesPaths.map(function(fileName, i){
mammoth.convertToHtml({path: fileName})
.then(/* ... */)
;
});
// Here filesHtml is empty and you don't know when will be filled!!
…这是肮脏的(见最后的评论)。
或者您可以简单地使用Promise.all()来收集结果:
var P = Promise.all(
filesPaths.map(function(fileName){
return mammoth.convertToHtml({path: fileName});
})
).then(function(resultArr){
return Promise.all(resultArr.map(function(result, i){
return {
text: text.value,
fileName: filesPaths[i],
};
}));
}).then(function(filesHtml){
/* Here you know filesHtml is fully filled */
});
P.then(function(filesHtml){
/* ...and here too */
});
用另一个选项来回应你自己的答案:
在循环中创建函数不是一个好主意,这是一个创建未知数量函数的好方法。如果你使用forEach循环,你会在它的回调函数中得到相同的封装。
var arr = ['a', 'b', 'c'];
function prom(thing) {
return Promise.resolve(thing);
}
for (var i = 0; i < arr.length; i++) {
prom(arr[i]).then(function(val){
console.log(`for: got val ${val} with arr[${i}]`);
});
}
// Logs:
// "for: got val a with arr[3]"
// "for: got val b with arr[3]"
// "for: got val c with arr[3]"
arr.forEach(function(val, index) {
prom(val).then(function(val){
console.log(`forEach: got val ${val} with arr[${index}]`);
});
});
// Logs:
// "forEach: got val a with arr[0]"
// "forEach: got val b with arr[1]"
// "forEach: got val c with arr[2]"
相关文章:
- 如何为javascript promise进行阻塞并返回解析结果
- async问题,JS Promise无法返回结果,但可以使用console.log
- 使用Node中的Q promise库对值数组顺序调用/执行相同的函数;并返回带有结果的新数组/集合
- 在多维数组中获取promise的结果
- 如何访问AngularJS promise链中上一个promise的结果
- 如何使用 Parse.promise javascript 定义一个承诺数组并获取结果数组 [parse.com]
- 在返回结果之前,我如何等待 jQuery.ajaxComplete in promise.done
- 使用 promise 将异步函数的结果作为“变量”返回
- JavaScript原生Promise对两个结果执行回调
- 用promise处理promise的数组结果
- ES7使用wait生成器从一系列promise中获取结果
- 为什么defered.promise在defered.resolve(myobject)之后的结果与myobject不同
- 当你想要所有结果而不管是否被拒绝时,用什么代替Promise.all()
- 什么'这是处理promise对象中错误结果的正确方法
- 如何在promise解析时手动将promise的结果获取到作用域变量中
- JS Promise无法返回结果
- request-promise -我如何从函数外的Promise获得结果?
- 承诺的循环.如何检测哪个promise现在返回结果
- 在下一次循环迭代之前等待promise结果
- Promise API -结合2个异步调用的结果