[英]Dynamically define function in Bluebird promise
我有一個我認為簡單的問題-但我根本無法解決。 我有一個正在使用的API,當我完成所有代碼后,該API返回一個function
供我調用。 我以為我可以將函數放到finally
調用中-但是看來我無法在Promise鏈中重新定義函數。
一個簡單的例子:
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 end"
? 本示例將始終打印"At the start"
。 如果我使用字符串而不是函數,它將按預期工作。
您需要將a
傳遞給finally
調用,然后才能從異步回調中覆蓋它( 經典方法) 。
您只需要在finally
回調中取消引用a
:
.finally(function() { a(); })
當然,請注意,重新定義函數很奇怪,並且可能有更好的方法來解決實際問題。 如果希望對某個函數有所承諾,則不要為該函數創建全局變量,而應執行.then(fn => fn())
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.