if-else流入承诺(蓝鸟)

vin*_*ayr 39 node.js promise bluebird

这是我的代码的简短版本.

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

if (conditionA) {
  fs.writeFileAsync(file, jsonData).then(function() {
    return functionA();
  });
} else {
  functionA();
}
Run Code Online (Sandbox Code Playgroud)

两种情况都要求functionA.有办法避免其他条件吗?我可以,fs.writeFileSync但我正在寻找一个非阻塞的解决方案.

Ber*_*rgi 61

我想你在找

(conditionA 
  ? fs.writeFileAsync(file, jsonData)
  : Promise.resolve())
.then(functionA);
Run Code Online (Sandbox Code Playgroud)

这是短的

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();
});
Run Code Online (Sandbox Code Playgroud)


Gob*_*ord 9

虽然这里的其他建议有效,但我个人更喜欢以下内容.

Promise.resolve(function(){
  if (condition) return fs.writeFileAsync(file, jsonData);
}())
.then()
Run Code Online (Sandbox Code Playgroud)

它的缺点是总是创造这个额外的承诺(相当小的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);
Run Code Online (Sandbox Code Playgroud)
Initial state
Run Code Online (Sandbox Code Playgroud)
实际上,在你的情况下,它只是

if (someCondition) return somePromise;
Run Code Online (Sandbox Code Playgroud)

在第一个.then()函数内部.