javascript - 如何使用 promises 异步读取多个文件,然后继续

标签 javascript node.js promise rsvp.js rsvp-promise

我不熟悉 promises 和使用 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);
});

我想做这样的事情:

loadFile(['src/index.txt', 'src/extra.txt', 'src/another.txt']).then( ...

我看过 arrays of promiseshash 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())

关于javascript - 如何使用 promises 异步读取多个文件,然后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28662333/

相关文章:

javascript - 组织结构图;固定水平定位?和画线?

Javascript 代码不适用于 IE11,但适用于所有其他浏览器

node.js - Express错误处理中的代码质量检查与隐式next()之间的冲突

javascript - React Formik 没有正确处理错误

javascript - Node.js 将数据返回到异步函数失败

events - ionic 2 : publish multiple events on Modal dismiss sometimes doesn't work

javascript - 检查 ios phonegap 中是否存在相机

javascript - 在移动其他元素时保存 Canvas 中元素的位置

javascript - 使用集群将 Socket.IO 扩展到多个 Node.js 进程

node.js - 浏览器未通过 BrowserSync 或实时服务器启动