如何在then()中传递bluebird回调的参数?

时间:2016-05-31 14:35:45

标签: javascript node.js promise bluebird

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

$http.post('api/values', ???)

这会更实际:

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

例如,Something( ... ) .then(console.log, "Done."); 就是这样:

setTimeout

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

3 个答案:

答案 0 :(得分:1)

  

此时此刻,我这样做了:

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

这是正确的方法。箭头功能已经缩短了很多。请注意,您可以放弃" {" ..." ;}"部分。

  

这会更实际:

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

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

  

我的目标是减少已经荒谬的代码量   承诺产生。

然后使用async / await语法和转换器。它就像

一样简单
await Something(…);
console.log("Done");
  

Bluebird有没有这方法呢?

如果您不想使用转换器但是在ES6环境中(如最近的Node.js),您可以使用生成器函数模仿async / await { {3}}

答案 1 :(得分:1)

该功能几乎与setTimeout相同。无论如何,IE9及以下版本都要求使用polyfill https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

以下是使用console.log的示例案例的解决方法。使用引用this的任何函数时要小心。您可以使用bind设置this的值或保留undefined。此外,它将在" Done"之后记录承诺的已解决值。由于该值自动作为bind的最后一个参数传递。

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

答案 2 :(得分:0)

@Bergi对你的问题给出了很好的答案。只是添加,如果您使用() => console.log("Done.")或其他一般回调,请将其作为一个单独的函数:

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

Something( ... )
  .then(afterSomething);
相关问题