如何在 then() 中为蓝鸟回调传递参数?

How to pass arguments for bluebird callback in then()?

我有一个 returns 承诺的电话。此时此刻,我这样做:

Something( ... )
  .then(()=>{console.log("Done.");});

这样会更实用:

Something( ... )
  .then(console.log, "Done.");

例如,setTimeout 是这样工作的:

setTimeout(console.log, 1000, "Done.");

Bluebird有什么方法吗?我的目标是使用这个 实用的 选项来减少 Promises 生成的已经荒谬的代码量。

At this moment, I do this:

Something(…).then(()=>{console.log("Done.");});

这是正确的做法。箭头函数已经大大缩短了它。请注意,您可以删除“{”...“;}”部分。

This would be more practical:

Something(…).then(console.log, "Done.");

不,不会。 then 的第二个参数是 onRejected 回调,不是字符串。你不能那样做。

My aim is to reduce the already ridiculous amount of code that Promises generate.

然后使用async/await 语法和转译器。就这么简单

await Something(…);
console.log("Done");

Does Bluebird have any method for this?

如果你不喜欢使用transpiler但是在ES6环境下(比如最近的Node.js),你可以使用生成器函数来模仿async/await Promise.coroutine.

该功能几乎是 setTimeout 独有的。无论如何,IE9 及以下版本需要一个 polyfill https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

以下是使用 console.log 的示例案例的解决方法。将它与任何引用 this 的函数一起使用时要谨慎。您可以使用 bind 设置 this 的值或保留 undefined。此外,它将在 "Done" 之后记录 promise 的解析值,因为该值被自动作为最后一个参数传递给 bind

Something( ... )
    .then(console.log.bind(undefined, "Done."));

@Bergi 很好地回答了你的问题。只是补充一下,如果你经常使用 () => console.log("Done.") 或其他一些通用回调,请将其作为一个单独的函数:

function afterSomething() {
  console.log("Done.");
}

Something( ... )
  .then(afterSomething);