简体   繁体   English

正确地从API返回Q承诺

[英]Return a Q Promise from an API Properly

I am developing an API that I would to return a promise. 我正在开发一个API,可以兑现承诺。 The returned promise is composed of several other promises, so I'm using Q.all and/or Q.allSettled. 返回的承诺由其他几个承诺组成,因此我正在使用Q.all和/或Q.allSettled。 The problem I'm running into is that the code never completes (see test). 我遇到的问题是代码永远不会完成(请参阅测试)。

I'm expecting to be able to call then/fail/etc on what's being return from addUsers, which is a Q.all or Q.allSettlted 我期望能够在addUsers返回的内容上调用then / fail / etc,这是Q.all或Q.allSettlted

API: API:

'use strict';

var Q = require('q'),
    mongoose = require('mongoose'),
    User = require('../models/user'),
    _ = require('underscore');


var addUsers = function (users) {
    var promises = _.map(users, function (user) {
        var newUser = new User(user);
        var promise = Q.nbind(newUser.save, newUser);
        return promise();
    });

    return Q.allSettled(promises);
};

module.exports.addUsers = addUsers;

Test: 测试:

'use strict';

var kraken = require('kraken-js'),
    express = require('express'),
    request = require('supertest'),
    should = require('chai').should(),
    userApi = require('../lib/userApi'),
    User = require('../models/user');

describe('#userApi tests', function() {

    it('should insert an array of users using the userApi addUsers method', function(done) {
        var users = [];
        var user1 = {
            firstName: 'test1',
            lastName: 'test1',
            password: 'abc123',
            email: 'me1@here.com',
            userName: 'test1'
        };
        var user2 = {
            firstName: 'test2',
            lastName: 'test2',
            password: 'abc123',
            email: 'me2@here.com',
            userName: 'test2'
        };
        var user3 = {
            firstName: 'test3',
            lastName: 'test3',
            password: 'abc123',
            email: 'me3@here.com',
            userName: 'test3'
        };
        users.push(user1);
        users.push(user2);
        users.push(user3);

        //call the api and handle the promise that is returned
        userApi.addUsers(users)
            .then(function(results) {
                should.exist(results);
                //other assumptions here
                done();
            })
            .fail(function(err) {
                done(err);
            })
    });
});

I'm not a big fan of q . 我不是q忠实q I think is too much magic, so I rather use the native (on node@0.11.x) Promise instead. 我认为这太神奇了,因此我宁愿使用本机(在node@0.11.x上) Promise

But if I understood it right, q.nbind is a wrapper around the node's standard function call. 但是,如果我理解正确, q.nbind就是该节点的标准函数调用的包装器。
Maybe I would mimic its behavior using the new promise API as something like this. 也许我会像这样使用新的Promise API模仿其行为。

promise = function () {
  return new Promise(function(resolve, reject){
    newUser.save(function(err, data){
      if (err) return reject(err)
      resolve(data)

    })
  })
}

I'm assuming that the newUser is a mongoose model, and newUSer.save only call the callback with an error parameter. 我假设newUser是猫鼬模型,并且newUSer.save仅使用错误参数调用回调。 Since data is undefined, maybe q doesn't call resolve with a falsy value. 由于data是不确定的,因此q可能不会使用伪造的值来调用resolve。

I would try running your tests with this version of addUsers instead. 我会尝试使用此版本的addUsers运行测试。

var Promise = Promise || require('es6-promise').Promise // polyfill
, mongoose = require('mongoose')
;

function addUsers (users) {
  return Promise.all(users.map(function(user){
    return new Promise(function(resolve, reject){
      var newUser = new User(user)
      ;
      newUser.save(function(err){
        if (err) return reject(err)
        resolve()
      })
    })
  }))
}

On the side, It looks like that the cool kids are using bluebird this days for their promise fix. 在侧面,看起来很酷的孩子们这几天正在使用bluebird来完成他们的承诺。
It has great error handling (which is a problem with the native promise) and allow for custom builds. 它具有出色的错误处理能力(这是本机Promise的问题),并且允许自定义构建。

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

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