Promise Undefined 而不是布尔值

Promise Undefined instead of boolean

我正在使用 Promise 库来获取另一个带有 cheerio 请求的 promise-request 库的结果,但我一直在获取 undefined

而不是布尔值
return Promise.try(function () {
        .....
    }).then(function () {
        return self.checkGroupJoined(id);
    }).then(function (data) {
        console.log(data);

和我的方法promise-request

this.checkGroupJoined = function (steam_id) {
    var options = {
        uri: 'url',
        transform: function (body) {
            return cheerio.load(body);
        }
    };

    return rp(options).then(function ($) {
        $('.maincontent').filter(function () {
            if ($(this).find('a.linkTitle[href="url"]').length > 0){
                return true;
            } else {
                return false;
            }
        });
    }).catch(function (err) {
        return error.throw('Failed to parse body from response');
    });
};

我应该 promisifyAll 图书馆吗?

您需要更改此部分

return rp(options).then(function ($) {
        // You are not returning anything here
        $('.maincontent').filter(function () {
            if ($(this).find('a.linkTitle[href="url"]').length > 0){
                return true;
            } else {
                return false;
            }
        });
    }).catch(function (err) {
        return error.throw('Failed to parse body from response');
    });

如果您将代码更改为此它应该可以工作。

return rp(options).then(function ($) {
        let found = false;
        $('.maincontent').filter(function () {
            if ($(this).find('a.linkTitle[href="url"]').length > 0){
                found = true;
            }
        });
        return found;
    }).catch(function (err) {
        return error.throw('Failed to parse body from response');
    });

我猜你真正想要的是

….then(function ($) {
    return $('.maincontent').find('a.linkTitle[href="url"]').length > 0;
}).…

这将 return 来自 promise 回调的布尔值,使其成为实现值。