你非常接近!你需要use之前的值;这应该是一个承诺。将reduce的初始值设置为Promise.resolve()
。然后在reduce函数内部,而不是Promise.resolve().then(...)
。你应该有类似的东西:
return previous
.then(function() { return upload(current); })
.then(function() { /* do stuff */ });
重要的是你return
这里。这将成为previous
下次调用reduce函数时。
你有很多问题upload
功能。这biggest问题是你传递变量的方式使得它很难阅读:)(并且容易出错!)
如果您只读取文本文件,请使用readAsText
反而。注意我已将其重命名为readFile
,因为这是一个更准确的名称。
// returns a promise with the file contents
function readFile(file) {
return new Promise(function (resolve) {
var reader = new FileReader();
reader.onload = function(e) {
resolve(e.target.result);
};
reader.readAsText(file);
};
}
那么你的减少就是:
files.reduce(function(previous, file) {
return previous
.then(function() { return readFile(file); })
.then(function(contents) {
// do stuff
});
}, Promise.resolve());
你有一个很大的错误upload_file
虽然有变数。该变量对于reduce函数的作用域来说是局部的,所以它只会undefined
inside upload
。将其作为参数传递:
function upload(upload_file) { ... }
旁注var
。这就是为什么即使你设置了upload_file
with var
在reduce函数内部,它将是调用该函数之前的任何内容upload
:
var a = 3;
function foo() {
var a = 4;
console.log(a); // 4
}
foo();
console.log(a); // 3