簡體   English   中英

在Bluebird Promise中動態定義功能

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM