[英]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
獲得拒絕承諾。
基本的理解
所有then
和catch
處理程序都創建一個新的Promise對象並返回它們,以便我們可以鏈接它們。
拒絕承諾時,拒絕處理程序將處理它,但如果拒絕處理程序不拒絕承諾,則鏈中的后續處理程序不會將承諾視為拒絕。
在您的情況下,當機器關閉時,您拒絕它並拒絕處理,
}).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.