2017-05-26 55 views
1

我有下面的代碼:的JavaScript塊流執行承諾

router.post('/', function(req, res, next) { 

     doAsyncStuff() 

     .then(ret=>{ 
      console.log('first then block') 
      if (/*something*/) 
      res.sendStatus(202); /*I want to stop the execution here. changing this in return res.sendstatus will not solve the problem*/ 
      else 
      return doanotherAsyncStuff() /*i could move the second then block here but i need another catch statment*/ 
     }) 

     .then(ret=>{ 
      console.log('second then block'); 
      res.sendStatus(200) 
     }) 

     .catch(err=>{ 
      console.log(err) 
      err.status = 503 
      next(err) 
     }) 

    }); 

我的問題是,當我if表達是真實的,我想打電話給res.sendstatus(202)和停止執行流程。但是我的代碼沒有做我想做的事情,因爲即使我的if表達式爲真,「second then block」仍然會被記錄下來。

我可以將第二個then塊移動到第一個塊中,在調用doanotherAsyncStuff()方法之後,但如果我這樣做,我需要另一個catch語句,並且我想只有一個catch語句任何調用的異步方法都會發生錯誤。

所以我的問題是:當我的if表達式爲真時,有沒有辦法阻止承諾流執行?

回答

0

只分開那些塊。在if中返回你想要的,在else調用另一個函數,在那裏你執行異步的東西,然後在那裏鏈接另一個然後阻塞,而不是在第一個之後緊接着。

並在第一個添加一個捕獲,然後在第一個承諾也捕獲錯誤。

0

不,你不能選擇哪一個後續的then從你的回調中執行。

只要你有什麼建議:

... 
    .then(ret => { 
     if (/*something*/) { 
      return res.sendStatus(202); 
     } 
     return doanotherAsyncStuff().then(function() { 
      return res.sendStatus(200); 
     }); 
    }) 
    .catch(err=>{ 
    ... 

編輯,因爲你是返回一個額外的承諾,到承諾鏈你不需要額外的抓,所以如果它失敗現有catch將調用無論如何。