简体   繁体   English

承诺返回值和嵌套

[英]Promise return value and nesting

I have a function createOne() that should try to find a MongoDB document or create it if it cannot be found. 我有一个函数createOne() ,它应尝试查找MongoDB文档或在找不到文档时创建它。 In either way, a promise should be returned and the promise resolved with doc : 无论哪种方式,都应返回一个promise并使用doc解决这个promise:

var createOne = function(category) {
    var self = this;

    return this.findOne({ slug: category.slug }).exec()
        .then(function(doc) {
            if (!doc) {                    
                return self.create(category); // wait to resolve until document created.
            }
        });
};

Both findOne().exec() and create() (should) return a promise. findOne().exec()create() (都应该)都返回一个Promise。

I tried out many different ways such as using Q.fcall, manually creating one with Q.defer() and others, but either the resolve value was missing, or the second { slug: 'foo' } was created as well even though the first already existed(?). 我尝试了许多不同的方法,例如使用Q.fcall,使用Q.defer()和其他方法手动创建一种方法,但是要么缺少可分辨的值,要么即使创建了第二种{ slug: 'foo' } ,首先已经存在(?)。

Following is my calling code: 以下是我的调用代码:

var data = [
    { slug: 'foo' },
    { slug: 'bar' },
    { slug: 'foo' } // <- shouldn't be created because of first 'foo'.
];

Q.fcall(function() {
    // [...]
}).then(function() {
    var promises = data.map(function(category) {
        return createOne(category); // <- calls createOne().
    });
    return Q.all(promises);
}).then(function(categories) {
    console.log(categories);
}).done();

How can I structure createOne() so that console.log(categories) returns the documents, whether they are found or created first? 如何构造createOne()以便console.log(categories)返回文档(无论是先找到还是先创建)?

Edit: When the collection is empty, only two documents should be created. 编辑:当集合为空时,仅应创建两个文档。 { slug: 'foo' } only once. { slug: 'foo' }仅一次。

It seems I have figured out how to call asynchronous functions sequentially and compose a final array of all their promises (and later resolved values). 看来我已经弄清楚了如何顺序调用异步函数并组成它们的所有promise(以及以后解析的值)的最终数组。

My solution is based on a great array.reduce example I found in a comment from kriskowal on Github. 我的解决方案基于一个很棒的array.reduce示例,我在kriskowal的Github 评论中找到了这个示例。

var data = [
    'Element 1', 'Element 2', 'Element 3'
];

function asyncMock(element) {
    console.log('Handle', element);
    return Q.delay(element + ' handled.', 500);
}

var promise = data.reduce(function (results, element) {
    return results.then(function (results) {
        return asyncMock(element).then(function(result) {
            results.push(result);
            return results;
        });
    });
}, Q([]));

promise.then(function(elements) {
    console.log('Finished:', elements);
}).done();

You can find a working demo here: http://jsfiddle.net/Lnvu4/ 您可以在此处找到有效的演示: http : //jsfiddle.net/Lnvu4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM