在node.js环境中使用Bluebird promise,我检查是否存在文件的三种可能变体中的任何一种或不存在(image.png/image.gif/image .jpg)在我的服务器上。如果这三个文件中有一个存在,它应该返回给用户。如果三个文件都不存在,则应返回默认图像。到目前为止,我想出了这个代码:Node.js Bluebird Promise:promise.any返回默认图像
var promise1 = new Promise(function(resolve, reject) {
fs.statAsync('./image.jpg')
.then(function(result) {
if(result){
resolve('jpg');
}
}).catch(function(err){
//foo
});
});
var promise2 = new Promise(function(resolve, reject) {
fs.statAsync('./image.gif')
.then(function(result) {
if(result){
resolve('gif');
}
})
.catch(function(err){
//foo
});
});
var promise3 = new Promise(function(resolve, reject) {
fs.statAsync('./image.png')
.then(function(result) {
if(result){
resolve('png');
}
})
.catch(function(err){
//foo
});
});
Promise.any([
promise1,
promise2,
promise3
]).then(function(result) {
res.sendfile("./image."+result);
}).catch(function(err){
res.sendfile("./default.png");
});
问题是:只要这三个文件中的一个存在,一切都运行得很好。但是我不能让它工作,以便在没有找到三个文件的情况下返回默认图像。
如果找不到图像,您需要在每个承诺中使用'reject' –
这是一种反模式,可以在使用'fs.statAsync()'已经返回的内容时创建这些新承诺。您可以在'.then()'处理程序中评估结果并根据需要更改已解析的状态。无需将这些包装在自己的新承诺中。事实上,你的一些错误是由于这个承诺包装,这是不必要的,容易出错。 – jfriend00