2014-10-28 67 views
36

这是我的代码的简短版本。if-else flow in promise(蓝鸟)

var Promise = require('bluebird'); 
var fs = Promise.promisifyAll(require("fs")); 

if (conditionA) { 
    fs.writeFileAsync(file, jsonData).then(function() { 
    return functionA(); 
    }); 
} else { 
    functionA(); 
} 

这两个条件都调用functionA。有没有办法避免其他条件?我可以做fs.writeFileSync但我正在寻找一个非阻塞解决方案。

+0

Promise专为异步任务控制而设计。为什么使用同步功能?你可以简单地检查'writeFileAsync'的返回值。 – CodeColorist 2014-10-28 03:44:55

回答

52

我认为你正在寻找

(conditionA 
    ? fs.writeFileAsync(file, jsonData) 
    : Promise.resolve()) 
.then(functionA); 

这是短期的

var waitFor; 
if (conditionA) 
    waitFor = fs.writeFileAsync(file, jsonData); 
else 
    waitFor = Promise.resolve(undefined); // wait for nothing, 
              // create fulfilled promise 
waitFor.then(function() { 
    return functionA(); 
}); 
2

你总是可以使用Promise.all()有条件的功能

var condition = ...; 

var maybeWrite = function(condition, file, jsonData){ 
    return (condition) ? fs.writeFileAsync(file, jsonData) : Promise.resolve(true); 
} 

Promise.all([maybeWrite(condition, file, jsonData),functionA()]) 
.then(function(){ 
    // here 'functionA' was called, 'writeFileAsync' was maybe called 
}) 

或者,如果你想functionA只有在文件被写入后才能调用,你可以分开:

maybeWrite(condition, file, jsonData) 
.then(function(){ 
    // here file may have been written, you can call 'functionA' 
    return functionA(); 
}) 
+0

我的*只有*这个方法的问题是可维护性。你为自己不得不“解决”问题而自责。这是Promise链的好处之一 - 你的逻辑是线性感觉。 – 2017-01-30 19:36:17

7

尽管这里有其他建议,我个人更喜欢以下。

Promise.resolve(function(){ 
    if (condition) return fs.writeFileAsync(file, jsonData); 
}()) 
.then() 

它的缺点是始终创造这个额外的承诺(相当小的国际海事组织),但看起来更清洁我的眼睛。您还可以在IIFE内轻松添加其他条件/逻辑。

编辑

实施这样的事情很长一段时间后,我现在已经肯定改变的东西稍微清晰。最初的承诺是建立不分所以它是更清晰简单地做:

/* Example setup */ 
 

 
var someCondition = (Math.random()*2)|0; 
 
var value = "Not from a promise"; 
 
var somePromise = new Promise((resolve) => setTimeout(() => resolve('Promise value'), 3000)); 
 

 

 
/* Example */ 
 

 
Promise.resolve() 
 
.then(() => { 
 
    if (someCondition) return value; 
 
    return somePromise; 
 
}) 
 
.then((result) => document.body.innerHTML = result);
Initial state
其实,在你的情况,简直是

if (someCondition) return somePromise; 

第一。那么()内功能。