I'm using SailsJs v0.11.3 and I want to use Promises to avoid using nested callback but I don't know how to return two objects from one stage (.then()
) to another one.
My code looks like this but I got undefined when trying to print start
param on the third .then
statement.
User.findOneById(userId)
.then(function (result) { // #1
return result;
}).then( function (result_a) { // #2
console.log('---------------- ' + result_a );
var result_b = User.findOneById(ownerId)
.then(function (result) {
console.log(result);
return result;
});
return [result_a, result_b];
}).then( function (start, finish) { // #3
console.log('***********************', start, finish);
// do something when is done
}).catch( function (err) {
// do something when is error
console.log(err);
res.json(err.status,
{
error: err
});
})
.done(function () {
res.json(200);
});
Console result:
---------------- [object Object]
*********************** [ { person_id: '567ab10de51dcf11001b066a',
email: '[email protected]',
permission_level: 3,
reset_password_token: null,
belongs_to: '0',
signin_count: 3,
status_active: true,
last_signin_at: '2016-01-05T17:55:49.595Z',
last_signin_ip: '0.0.0.0',
encrypted_password: '$2a$10$tDSUsXm7nn2p4r8FczpCrubbTig/7hJmy3W5u5hrcmMHAiVBXYZ/C',
id: '567ab10de51dcf11001b0669' },
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: undefined } ] undefined
{ person_id: '565f57b7cd451a110063eef9',
email: '[email protected]',
permission_level: 1,
reset_password_token: '353635663537623763643435316131313030363365656638',
belongs_to: '0',
signin_count: 1,
status_active: false,
last_signin_at: '2015-12-02T20:42:30.434Z',
last_signin_ip: '0.0.0.0',
encrypted_password: '$2a$10$37EHaE6oED65gFHqh9sE0OBOTeD.txl8DTNYLxJwgws6NIwNQ73Ky',
id: '565f57b7cd451a110063eef8' }
So, I'd like to know how can I return two objects or variables in the second .then
to the third .then
. I mean the result from the first query and another result made on the second query and receive those in the third .then
?
I hope to explain my problem in the right way. Thanks in advance!
#3 .then
to look like this:.spread(function (start, finish) { // #3
. Just change.then
to.spread
and it works. Thanks a lot! – Undefined