【问题标题】:Promises: Give status update without returning from fnPromises: 提供状态更新而不从 fn 返回
【发布时间】:2017-10-10 10:44:35
【问题描述】:

我有一个调用三个异步函数的函数。 我想在每次完成这些功能之一时通知被调用者,以向用户显示操作的进度。

有没有办法在不从 fn 返回的情况下“通知”被调用者?

function updateDataset(...) {
    return a().then(function () {
        console.log("[someService] Task 1 done...");

        return b(...).then(function (entries) {
            console.log("[someService] Task 2 done...");

            var requests = c(entries);

            return Promise.all(requests).then(function () {
                console.log("[someService] Task 3 done...");

                return true;
            });
        });
    });
}

被调用者如下所示:

someService.updateDataset(...).then(function (isSucc) {
    //Do stuff
});

如果我可以将.notified() 链接到承诺链,那就太棒了...

【问题讨论】:

标签: javascript promise


【解决方案1】:

你可以传递一个回调并在那里处理通知,另外你可以“扁平化”链,这样每个承诺都会返回,并且你在另一个 .then 中没有 .then

我对您的代码进行了一些重构,只是为了向您展示一种可能的方法。

function updateDataset(notificationCb) {
    return a()
    .then(function () {
        console.log("[someService] Task 1 done...");
        notificationCb(1); //first ended
        return b(...);
    })
    .then(function (entries) {
        console.log("[someService] Task 2 done...");
        var requests = c(entries) ;
        notificationCb(2); //second ended
        return Promise.all(requests);
     })
    .then(function () {
       console.log("[someService] Task 3 done...");
       //here there's no need to call the callback because the fn returns to the caller
       return true;
    });
}

和调用者:

someService.updateDataset(function(notification){
 //here you choose the strategy to handle the notification
 if(notification === 1){ 
   //first has ended.. etc.
 } else{

 }
})
.then(function (isSucc) {
    //Do stuff
});

【讨论】:

    猜你喜欢
    • 2017-12-08
    • 1970-01-01
    • 2018-09-28
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2020-06-29
    相关资源
    最近更新 更多