如何用promise来asynchronous读取多个文件,然后继续
我刚刚承诺并使用rsvp实现。
我想asynchronous读取文件列表,然后只有在读取完所有文件后才能继续执行另一个任务。
我已经有了基本的结构来读取一个文件,并链接到下一个任务:
var loadFile = function (path) { return new rsvp.Promise(function (resolve, reject) { fs.readFile (path, 'utf8', function (error, data) { if (error) { reject(error); } resolve(data); }); }); }; loadFile('src/index.txt').then(function (data) { console.log(data); return nextTask(data); }).then(function (output) { //do something with output }).catch(function (error) { console.log(error); });
我想要做这样的事情:
loadFile(['src/index.txt', 'src/extra.txt', 'src/another.txt']).then( ...
我在文档中看到了承诺和承诺的 哈希 数组 ,但我不知道哪一个是最相关的,或者如何使用它们。 我需要在上面的问题的背景下使用他们的例子来理解他们。
你想使用RSVP.all()
:
var promises = ['path1', 'path2', 'path3'].map(loadFile); RSVP.all(promises).then(function(files) { // proceed - files is array of your files in the order specified above. }).catch(function(reason) { console.log(reason); // something went wrong... });
随意做promises
一个对象,并使用RSVP.hash()
来代替:
var promises = { file1: loadFile('path1'), file2: loadFile('path2'), file3: loadFile('path3') }; RSVP.hash(promises).then(function(files) { // files is an object with files under corresponding keys: // ('file1', 'file2', 'file3') }).catch(function(reason) { console.log(reason); // something went wrong... });
(感谢@Benjamin Gruenbaumbuild议使用.map()
)