2017-05-11 6 views
1

私は3つの非同期関数を呼び出す関数を持っています。 私は、これらの機能の1つが実行されるたびに、ユーザーにアクションの進行状況を知らせるために、呼び出し先に通知したいと思います。約束:fnから戻ることなくステータスを更新

fnから戻らずに着信先に「通知する」方法がありますか?

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

私は約束チェーンへ.notified()をチェーンことができればそれは素晴らしいだろう...

+1

を参照してください:http://stackoverflow.com/q/32909694/2446102 – Ginden

答えて

2

あなたがコールバックを渡し、通知を扱うことができる:

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; 
      }); 
     }); 
    }); 
} 

呼び出し先は次のようになりますさらに、すべての約束が返されるようにチェーンを「平坦化」することができ、.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 
}); 
関連する問題