Promises as function return on node.js

5

I'm using the Sequelize.js framework. to perform queries on the database, the result of the find function returns an object with 3 methods: success , error and complete

Ex:

models.ItensPedido.findAll( {where : {PedidoId: req.params.pedidoId}})
    .success( function( pedidos ) {
    res.send(200, pedidos);
    next;
})
.error( function(err) {
    console.log("Erro ao listar itens do pedido", req.params, err);
    res.send(500, "Erro ao listar itens do pedido: ", err);
    next();
})

I tried to do a function that returned the same way, but without success

function validateLogin( pemail, ppwd ) {
    return function () {
        var successfull = false;
        var error;
        var user;

        exports.success = function ( userSuccess ) { 
            if (!successful) retrun; 

            userSuccess(user);
        }
        exports.error = function ( userError ) {
            if (!error) {retrun;} 
            userError(error);
        }

    models.User.find( { where: Sequelize.and({email: pemail}, {pwd: ppwd}) })
        .success( function (foundUser) {
           if (!user) {error = "User not found."; return;}
           user = foundUser;
           successfull = true;
        })
        error( function (err) {
           error = err;
        })

    }
}

But I always have a return that the object does not have a method success

The idea is to be able to use it as follows:

validateLogin( "[email protected]", "123456")
    .success( { //logica de sucesso  } )
    .error( { //logica de erro } );

Today I get the expected result as follows, passing the callbacks to the method:

validateLogin( "[email protected]", "123456", doOnSuccessLogin, doOnErrorLogin);

But for this I need the two callbacks to be declared within the same function by the closure of the restify parameters to answer the call rest

How to return an object, asynchronously, with methods after the query execution, in nodejs?

    
asked by anonymous 13.06.2014 / 21:22

1 answer

3

There are parts of your code that I do not quite understand, but answering the question returns an object and not a function:

function validateLogin( pemail, ppwd ) {
    return {
       success: function() {},
       error: function() {}
    };
}

Considering your update, I suggest returning the "promise" itself (or whatever the Sequelize implemented there) returned by models.User.find . So:

function validateLogin( pemail, ppwd ) {
    return models.User.find( { where: Sequelize.and({email: pemail}, {pwd: ppwd}) });
}

// USO:

validateLogin( "[email protected]", "123456")
    .success( function(foundUser) {  } )
    .error( function(err) { } );
    
13.06.2014 / 21:35