【问题标题】:Bluebird spread returns undefined over ping moduleBluebird spread 在 ping 模块上返回 undefined
【发布时间】:2016-01-13 01:18:48
【问题描述】:

我有以下测试代码;

var Promise = require("bluebird");
var ping = require('ping');
Promise.promisifyAll(ping);

Promise.some([
    ping.sys.probe("google.com"),
    ping.sys.probe("yahoo.com"),
    ping.sys.probe("microsoft.com"),
    ping.sys.probe("facebook.com")
], 2).spread(function (first, second) {
    debugger;
    console.log(first, second);
}).catch(Promise.AggregateError, function (err) {
    err.forEach(function (e) {
        console.error(e.stack);
    });
}).error(function(err){
    console.log("error: " + err);
});

//    ping.sys.probe("google.com", function(isAlive){
//         var msg = isAlive ? 'host ' + "google.com" + ' is alive' : 'host ' + "google.com" + ' is dead';
//         console.log(msg);
//     });

由于某种原因,函数进入了扩展处理程序,但两个值都未定义。 ping module 自然是支持 Promise 的,而 promisifyAll 在那里可能是不必要的。

我的实现中会缺少什么?

【问题讨论】:

  • 它会传播到您的错误处理程序吗? promisify 需要一个节点 err, result 回调,而 probe 方法只返回一个参数。您可能需要创建自定义函数而不是 promisify 或使用 this。
  • 其实查看库后可以使用ping.promise.probe('site')
  • @BenFortune 啊,我错过了这一点!感谢您的注意,在我使用之后,它按预期工作。

标签: node.js promise ping bluebird


【解决方案1】:

您需要改用promise 方法,它们位于ping.promise。图书馆不需要承诺,所以你可以把它拿出来。

Promise.some([
    ping.promise.probe("google.com"),
    ping.promise.probe("yahoo.com"),
    ping.promise.probe("microsoft.com"),
    ping.promise.probe("facebook.com")
], 2).spread(function (first, second) {
    debugger;
    console.log(first, second);
}).catch(Promise.AggregateError, function (err) {
    err.forEach(function (e) {
        console.error(e.stack);
    });
}).error(function(err){
    console.log("error: " + err);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多