这是我的代码的简短版本。
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,但我正在寻找一个非阻塞的解决方案。
发布于 2014-10-28 11:28:09
我想你要找的是
(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();
});发布于 2016-04-21 08:45:46
虽然这里的其他建议是可行的,但我个人更喜欢下面的建议。
Promise.resolve(function(){
if (condition) return fs.writeFileAsync(file, jsonData);
}())
.then()它的缺点是总是创建这个额外的承诺(相当小的IMO),但在我看来要干净得多。您还可以轻松地在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;在第一个.then()函数内部。
发布于 2014-10-28 11:29:35
您可以始终将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();
})https://stackoverflow.com/questions/26599798
复制相似问题