如何使用promises异步读取多个文件,然后继续 [英] How to read multiple files asynchronously with promises, then proceed

查看:110
本文介绍了如何使用promises异步读取多个文件,然后继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是承诺并使用 rsvp 实施的新手。

I'm new to promises and using the rsvp implementation.

我想异步读取文件列表,然后只有在读完所有文件后才进行另一项任务。

I want to asynchronously read a list of files, then proceed to another task only when all files have been read.

我是得到读取一个文件的基本结构,并链接到下一个任务:

I've got as far as the basic structure to read one file, and chain to the next task:

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( ...

我见过承诺数组文档中的承诺哈希,但我不知道哪个是最相关的,或者如何使用它们。我需要在上述问题的上下文中使用它们的一个例子来理解它们。

I've seen arrays of promises and hash of promises in the docs, but I don't know which is most relevant, or how to use them. I need an example of their use in the context of my problem above to understand them.

推荐答案

你想使用 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...
});

随意制作承诺一个对象并使用 RSVP.hash()代替:

Feel free to make promises an object and use RSVP.hash() instead:

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()

(thanks to @Benjamin Gruenbaum for suggestion to use .map())

这篇关于如何使用promises异步读取多个文件,然后继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆