簡體   English   中英

Nodejs Promise.all()始終解析

[英]Nodejs Promise.all() resolving always

我是新的承諾。 我試圖ping一些機器來檢查它們是否處於活動狀態。 我正在使用本機NodeJS承諾。 我的ping功能:

function ping(addr) {
    return new Promise(function(resolve, reject) {
        var args = ['-n', '1', '-w', '5000'];
        args.push(addr);
        var ls = cp.spawn('ping.exe', args);

        ls.on('error', function (e) {
            reject(Error('There was an error while executing the ping'));

        });

        ls.on('exit', function (code) {
            if(code === 0) {
                resolve({host: addr});
            } 
            else {
                reject(Error(addr + " is  down!"));
            }

        });
    });

}

現在,我有一個從JSON讀取的數組中的機器的詳細信息:

gulp.task('pingNodes', ['readConfigJSON'], function () {

    var batches = ConfigJSON.NodeDetails.Batch1.concat(ConfigJSON.NodeDetails.Batch2);
    var pingPromises = batches.map(function (host) {
        return ping(host.Name)
            .then(function (res) {
                console.log(res.host + " is  up!");
            }).catch(function (err) {
                console.log(err);
            });
    });
    return Promise.all(pingPromises).then(function(){console.log("All nodes are up!")});
});

現在它即使某個節點關閉也不會拒絕:

[16:58:46] Starting 'init'...
Starting Deployment
[16:58:46] Finished 'init' after 135 µs
[16:58:46] Starting 'readConfigJSON'...
[16:58:46] Finished 'readConfigJSON' after 204 µs
[16:58:46] Starting 'pingNodes'...
machine1 is  up!
machine2 is  up!
machine3 is  up!
[Error: machine4 is  down!]
All nodes are up!
[16:58:49] Finished 'pingNodes' after 2.54 s

要解決此問題,請在catch處理程序中再次拋出錯誤,如下所示

}).catch(function (err) {
    console.log(err);
    throw err;
});

或刪除catch處理程序。 基本上,您應該讓拒絕流入鏈中,以便Promise.all在機器Promise.all獲得拒絕承諾。


基本的理解

  1. 所有thencatch處理程序都創建一個新的Promise對象並返回它們,以便我們可以鏈接它們。

  2. 拒絕承諾時,拒絕處理程序將處理它,但如果拒絕處理程序不拒絕承諾,則鏈中的后續處理程序不會將承諾視為拒絕。

在您的情況下,當機器關閉時,您拒絕它並拒絕處理,

}).catch(function (err) {
    console.log(err);
});

但是, catch處理程序返回一個未被拒絕的promise。 所以, Promise.all實際上獲得了一個未被拒絕的Promise對象。 這就是為什么一旦發現其中一台機器出現故障就不會停止。

您可以使用以下程序確認此理解

var a = Promise.resolve(1)
    .then(function (e) {
        throw e;
    })
    .catch(function (e) {
        // This is what you are doing if the machine is down
        console.log(e);

        // No rejection here, so `then` will be called.
        // Uncomment the throw to see 
        // throw e;
    });

a.then(function (e) {
    console.log("Inside then")
});

a.catch(function (e) {
    console.log("Inside catch")
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM