在 Bluebird promise 中动态定义函数

Dynamically define function in Bluebird promise

我遇到了一个我认为很简单的问题 - 但我就是无法解决它。 我有一个 API,我正在使用那个 returns 一个 function 供我在所有代码完成后调用。我原以为我可以将函数放在 finally 调用中 - 但似乎我无法在承诺链中重新定义函数。

一个简单的例子:

let a= function() {console.log("at the start");};
BbPromise.resolve("Executing")
    .tap(console.log)
    .then(function() {a = function() {console.log("at the end");}})
    .finally(a); 

最后,我将如何让 "At the end" 打印出来?此示例将始终打印 "At the start"。如果我使用字符串而不是函数,它会按预期工作。

在从异步回调覆盖它之前,您将 a 传递给 finally 调用 - a classic.

您只需在 finally 回调中取消引用 a

.finally(function() { a(); })

当然,请注意重新定义函数很奇怪,可能有更好的方法来解决您的实际问题。如果你希望得到一个函数的承诺,你不应该为函数创建一个全局变量,而是 .then(fn => fn()).