小编k7s*_*per的帖子

Bluebird Promise.any() 提前拒绝?

我在我所有的 Node.js 项目中都使用了 Promise 库 Bluebird。为了从文件路径列表中获取第一个现有文件的内容,我Promise.any成功使用如下:

Promise.any([
   './foo/file1.yaml',
   './foo/file2.yaml',
   './foo/file3.yaml'
], function(filePath) {
    _readFile(filePath);
}),then(function(fileContent) {
    _console.log(fileContent);
});
Run Code Online (Sandbox Code Playgroud)

我的问题是,Promis.any如果我在读取文件时遇到与“找不到文件”不同的错误,我该如何提前退出循环?以下代码说明了我的问题:

Promise.any([
   './foo/file1.yaml',
   './foo/file2.yaml',
   './foo/file3.yaml'
], function(filePath) {
    _readFile(filePath)
    .catch(function(err) {
       var res = err;
       if (err.code == FILE_NOT_FOUND) {
          // continue the Promise.any loop
       } else {
          // leave the Promise.any loop with this error
          err = new Promise.EarlyBreak(err);
       }
       Promise.reject(err);
    });
}).then(function(fileContent) {
    _console.log(fileContent);
}, function(err) {
    // the first error different from FILE_NOT_FOUND
});
Run Code Online (Sandbox Code Playgroud)

可能 …

javascript promise bluebird

2
推荐指数
1
解决办法
1223
查看次数

标签 统计

bluebird ×1

javascript ×1

promise ×1