2017-09-04 87 views
0

我正在使用令人驚歎的async.js庫進行項目。試圖瞭解承諾的使用,但我不能。未處理的承諾拒絕async.js瀑布內的警告

我實現下面的代碼:

function connect(){ 
    return new Promise(function (resolve, reject) { 
     bar.getConnection(server, function(err, conn){ 
      if(err) { 
       reject("An error. " + err); 
      } 
      else{ 
       resolve("Ok. Connected to: " + conn.serverAddress); 
      } 
     }); 
    }); 
} 

然後在async waterfall

exports.getRequest = function(callbk){ 
    (function(callback) { 
     async.waterfall([ 
      function (next) { 
       connect().then(function (result) { 
        console.log(result); 
        next(); 
       }).catch(function (e) { 
        // If something gets an error on the next function, this catch fires 
        // And the 'next(e)' does not execute 
        console.log("An error here"); 
        next(e); 
       }); 
      }, 
      function (next) { 
       // do something .... and get a result 
       // but if something gets an error here, fires the 'catch' on 'connect' 
       next(null, result); 

      }, 
      function (err, result) { 
       if(err) { 
        callback(true, "" + err); 
       } 
       else { 
        callback(false, result); 
       } 
      } 
     ]); 
    })(function(error, result) { 
     callbk(error, result); 
    }); 
} 

但是,如果事情在第二功能得到錯誤的「瀑布」第一的catch內功能上升,它附帶:

(node:8984) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called. 
(node:8984) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

我知道使用Promise和async.js並不是一個好主意,但我想明白爲什麼。

我已經看到幾個相同的答案,但我仍然無法解決它。

+2

請勿混用的承諾, 'async.js'模塊,使用一個。 – alexmac

+0

您展示的代碼對我來說看起來很不錯,您確定,它是您收到拒絕警告的正確位置嗎? –

+0

@JohannesMerz是的。我已經測試過,那就是這個地方。我相當確定。 – robe007

回答

1

我知道這不是一個好主意,用承諾與async.js

好!

但我想明白爲什麼。

如果任何在你的回調(包括一個傳遞給getRequest)的一個人扔從then回調next();通話異常,承諾會拒絕。不僅如此,拒絕承諾的catch也會執行,現在調用next(e); - 這將使async.js抱怨next回調被調用兩次,忽略e並拒絕第二個承諾,併發生新的異常。此拒絕不會在任何地方處理,並會記錄到您的控制檯。

看一看在difference between .then(…, …) and .then(…).catch(…) - 如果你使用的是前者,那麼原來的異常將拒絕承諾,並得到記錄爲未處理的,沒有回調被調用兩次:

connect().then(function (result) { 
    console.log(result); 
    next(null, e); 
}, function (e) { 
    console.log("An error here"); 
    next(e); 
}); 
+0

對不起,但是......什麼意思是'前'? – robe007

+1

@ robe007它指的是'.then(...,...)',而'.then(...).catch(...)'是「後者」 – Bergi

+0

感謝我的朋友的貢獻。你能否請你在我的答案中解釋一下'.then(...,...)和.then(...).catch(...)'之間的區別。 – robe007

相關問題