mtm*_*ald 6 javascript node.js promise rsvp.js rsvp-promise
我是承诺并使用rsvp实现的新手.
我想异步读取文件列表,然后只有在读取了所有文件后才进入另一个任务.
我已经有了基本结构来读取一个文件,并链接到下一个任务:
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);
});
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情:
loadFile(['src/index.txt', 'src/extra.txt', 'src/another.txt']).then( ...
Run Code Online (Sandbox Code Playgroud)
我在文档中看到过承诺和承诺的数组,但我不知道哪个是最相关的,或者如何使用它们.我需要在上面的问题的上下文中使用它们的一个例子来理解它们.
你想用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...
});
Run Code Online (Sandbox Code Playgroud)
随意制作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...
});
Run Code Online (Sandbox Code Playgroud)
(感谢@Benjamin Gruenbaum建议使用.map())
| 归档时间: |
|
| 查看次数: |
1346 次 |
| 最近记录: |