javascript - Bluebird 相当于 Q Promise.post

标签 javascript promise bluebird

我目前正在从 Q 迁移到 Bluebird。

我有以下内容来包装对 MongoDB 的调用:

DB.prototype.find = function(collectionName /*, query, projection, opt*/){
    if (arguments.length < 1) {
        return Promise.reject(new _Error("argumentsError", "DB:find expected collection name"));
    }

    var args = new Array(arguments.length);
    args[0] = 'findAsync';
    for (var i=1, l=arguments.length; i<l; i++) {
        args[i] = arguments[i];
    }

    var promise = this.getCollection(collectionName);
    return promise.call.apply(promise, args);
}

我的问题是,使用 Q 我可以简单地使用 .post('findAsync', args) 而不是 apply 上的 >promise.call。即使这段代码可以工作,它也需要很多 LOC。 Bluebird 有更好的方法吗?

最佳答案

Even if this code works, its a lot of LOC just for this.

我不认为很多 LOC 来自 .apply() 语句。它将参数复制到数组非常麻烦,事实上,如果您使用 Q 的 .post() 方法,您会得到完全相同的 3 行。

如果您真的关心,您可以将其缩短为

DB.prototype.find = function(collectionName /*, query, projection, opt*/) {
    if (!arguments.length)
        return Promise.reject(new _Error("argumentsError", "DB:find expected collection name"));

    var args = Array.prototype.slice.call(arguments);
    args[0] = 'findAsync';
    return Promise.prototype.call.apply(this.getCollection(collectionName), args);
}

(尽管这可能有 performance implications )。您可能还想尝试一个简单的

    arguments[0] = 'findAsync';
    return Promise.prototype.call.apply(this.getCollection(collectionName), arguments);

(当然假设严格模式)。

Is there a better approach with bluebird?

我不这么认为。您的代码注释似乎表明您无论如何都需要三个参数,您可能只想将它们命名为参数并将它们显式传递给 .call()

如果您正在寻找真正优越的方法,请使用带有剩余参数和展开参数的 ES6:

DB.prototype.find = function(collectionName, ...args) {
    if (!arguments.length)
        return Promise.reject(new _Error("argumentsError", "DB:find expected collection name"));

    return this.getCollection(collectionName).call('findAsync', ...args);
}

关于javascript - Bluebird 相当于 Q Promise.post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32592486/

相关文章:

javascript - 循环中的 Bluebird promise

javascript - Highcharts JS 与数据库中的值

javascript - 谷歌抓取: Now parsing JavaScript results?

javascript - D3 树布局 - 具有子节点的子节点之间的距离

javascript - 如何在 JavaScript 中开始 promise ?

javascript - promise 解决无效

javascript - Node.js Promise.all() 挂起

javascript - 带有回调错误的 Promise catch 中的无限循环

node.js - 等待所有 promise 在 nodejs 中用 Bluebird 完成

javascript - 使用数组或字符串设置选择的 Semantic-UI 下拉列表