javascript - 在循环使用 Mongoose 查询时有希望 - Node Bluebird

标签 javascript node.js mongodb bluebird

我想在 map 内的每个循环内进行查询,然后一旦完成循环和查询就执行其他操作:

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 被控制台之前进行控制台。这意味着我无法对数据做任何事情。

最佳答案

来自bluebird.done :

.done([Function fulfilledHandler] [, Function rejectedHandler ]) -> void

Like .then(), but any unhandled rejection that ends up here will be thrown as an error. Note that generally Bluebird is smart enough to figure out unhandled rejections on its own so .done is rarely required. As explained in the error management section, using .done is more of a coding style choice with Bluebird, and is used to explicitly mark the end of a promise chain.

因此,在您的 Promise.map 中,它只获得一个 undefined 数组或其他内容,但不是 Promise,因此 map 是拿到 map 后就解决了。使用 .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);
});

关于javascript - 在循环使用 Mongoose 查询时有希望 - Node Bluebird,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31853690/

相关文章:

javascript - Ajax 以 dd/mm/yyyy 格式获取日期

JavaScript 正则表达式\G + 等效偏移量

Node.js/Connect 使用现有的 Connect.SID

javascript - PHPStorm 中用于 browserify 的相对路径

Javascript + AJAX + Facebook

mongodb - nodejs - mongodb - 如何找到 a != b 的所有位置?

c++ - 使用 CMake 生成 Visual Studio 2017 项目

java - 不兼容的类型 : inference variable T has incompatible bounds equality constraints: capture#1 of ? 扩展了 java.lang.Object

javascript - 基于 url 中的选择的下拉突出显示?

javascript - Vue JS 应用程序上的 Passport JS 身份验证