2017-09-04 20 views
0

私は驚くべきasync.jsライブラリを使ってプロジェクトを進めています。約束の使用を理解しようとしていますが、私はできません。未処理プロミス拒否警告async.jsの滝の中で

私は次のコードを実装:何かが「滝」最初のcatch内の第二の機能に間違って取得する場合、

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

しかし:async waterfall

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

そしてを機能が立ち上がり、それに付属しています:それは付属しています:

(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. 

私はasync.jsでPromisesを使うのは良い考えではないことを知っていますが、なぜそれを理解したいのですか?

私は同じことに関してはほとんど答えを見ませんでしたが、まだ解決できません。

+2

は約束を混在させないでください。また、 'async.js'モジュールは、何かを使用します。 – alexmac

+0

あなたが見せているコードは、私にはうまく見えますが、拒否警告を受け取った正しい場所ですか? –

+0

@JohannesMerzはい、そうです。私はテストして、それは場所です。私はかなり確信しています。 – robe007

答えて

1

私はそれがasync.js

良いとの約束を使用するためには良い考えではありません知っています!

しかし、私はその理由を理解したい。

thenコールバックでそのnext();コールからの例外をスローしない(getRequestに渡されたものを含む)あなたのコールバックのいずれかで、何場合は、約束を拒否します。それだけでなく、拒否された約束のcatchも実行されます。今度はnext(e);を呼び出します。これにより、nextコールバックが2回呼び出され、eが無視され、新しい例外で2番目の約束が拒否されます。この拒否はどこでも処理されず、コンソールに記録されます。

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(...).catch(...)」の違いについて少し説明してください。 – robe007

関連する問題