我对承诺和使用不熟悉rsvp https://github.com/tildeio/rsvp.js执行。
我想异步读取文件列表,然后仅在读取所有文件后才继续执行另一个任务。
我已经了解了读取一个文件并链接到下一个任务的基本结构:
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( ...
我见过一连串的承诺 https://github.com/tildeio/rsvp.js/#arrays-of-promises and 承诺的哈希值 https://github.com/tildeio/rsvp.js/#hash-of-promises在文档中,但我不知道哪个最相关,或者如何使用它们。我需要一个在我的问题上下文中使用它们的示例来理解它们。
你想使用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 Gruenbaum 提出使用建议.map()
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)