【问题标题】:Promise Undefined instead of boolean承诺未定义而不是布尔值
【发布时间】:2017-02-09 20:14:13
【问题描述】:

我正在使用 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 图书馆吗?

【问题讨论】:

  • 你...没有从rp(options).then(function ($) {返回任何东西。您只需选择一些元素,将它们过滤到一个子集,然后......扔掉它。
  • 那么如何返回呢?因为我在确定是否找到它后返回。
  • 你想返回什么?因为现在你只是在过滤一组元素......没有什么可以返回?
  • 你不需要因为在人们感到卡住时不断询问有关编程问题的地方提出有关编程的问题而对我投反对票 :) 问候!

标签: javascript promise bluebird cheerio


【解决方案1】:

我猜你真正想要的是

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

这将 return 来自承诺回调的布尔值,使其成为履行值。

【讨论】:

    【解决方案2】:

    您需要更改此部分

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

    【讨论】:

    • 是的,这就是我错过的东西,高五!
    • 为什么这么复杂?为什么要使用filter 进行循环(而不是each)?
    猜你喜欢
    • 2021-02-13
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    相关资源
    最近更新 更多