【问题标题】:Promising whilst looping through with mongoose queries - Node Bluebird使用 mongoose 查询循环时有希望 - Node Bluebird
【发布时间】:2015-08-06 18:50:09
【问题描述】:

我想在地图的每个循环内进行查询,然后在完成循环后执行其他操作:

Promise.map(results, function (item, index) {
         return Clubs.findAsync({name: name})
        .then(function (err, info) {
            if (err) {console.info(err); return err};
            console.info(info);
            return info;
        })
        .done(function (info) {
            return info;
        });
    }).done(function (data) {
        console.info('done');
        req.flash('success', 'Results Updated');
       res.redirect('/admin/games/'+selectedLeague);
    });

在这种情况下,done 将在 info 被控制之前进行控制。这意味着我无法对数据做任何事情。

【问题讨论】:

    标签: javascript node.js mongodb bluebird


    【解决方案1】:

    来自bluebird.done

    .done([Function fulfilledHandler] [, Function deniedHandler ]) -> 无效

    与 .then() 类似,但任何最终出现在此处的未处理拒绝都将是 作为错误抛出。请注意,通常蓝鸟足够聪明 自行找出未处理的拒绝,因此 .done 很少见 必需的。如错误管理部分所述,使用 .done 是 更多的是 Bluebird 的编码风格选择,用于明确 标记承诺链的结束。

    所以在您的Promise.map 中,它只获得undefined 或其他东西的数组,而不是Promise,因此地图在获得地图后得到解决。使用.then 返回Promise

    Promise.map(results, function (item, index) {
         return Clubs.findAsync({name: name})
        .then(function (err, info) {
            if (err) {console.info(err); return err};
            console.info(info);
            return info;
        })
        // vvvv use `.then` here, not `.done`, done returns nothing, not promise.
        .then(function (info) {
            return info;
        });
    }).done(function (data) {
        console.info('done');
        req.flash('success', 'Results Updated');
       res.redirect('/admin/games/'+selectedLeague);
    });
    

    【讨论】:

    • 有点震惊。 .done 只是为了向自己表明我在这里完成了:) 我认为这是承诺 101。不错的一个:)
    猜你喜欢
    • 2016-08-20
    • 2016-02-15
    • 2016-08-17
    • 2016-05-08
    • 2015-11-08
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    相关资源
    最近更新 更多