7

我是新的承诺和使用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( ...

我在文档中看到了一系列承诺和承诺散列,但我不知道哪个最相关,或者如何使用它们。我需要一个在我上面的问题的上下文中使用它们的例子来理解它们。

4

1 回答 1

7

你想使用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()

于 2015-02-22T19:39:32.190 回答