I wanted to simplify this method:
var Q = require('q');
module.exports.save = function (db, item) {
return Q.promise(function (resolve, reject) {
db.items.save(item, function (e, result) {
if (e) {
reject(e);
} else if (result) {
resolve(result);
} else {
reject('object expected');
}
});
});
};
which worked fine and the promise returned an object from the database.
I replaced it with just
module.exports.save = function (db, item) {
return Q.ninvoke(db.items, 'save', item);
};
which also works fine but resolves with an array with a single element and this element is the same as in the original code.
Why is it doing this? How to make it not put the result into an array?
but resolves with an array with a single element
I don't think so. It should be an array of length 2, with the first element being the saved item(s) and the second being a "lastError" object. From the code of the save method:
if (err) return cb(err);
if (doc === 1) {
cb(err, args[0], lastErrorObject);
} else {
// The third parameter is a faked lastErrorObject
cb(err, doc, { n : 0});
}
When the callback is called with no error and more than 1 result argument, Q.ninvoke automatically converts this into an array with which the promise is resolved (from makeNodeResolver):
function nodecallback(error, value) {
if (error) {
deferred.reject(error);
} else if (arguments.length > 2) {
deferred.resolve(array_slice(arguments, 1));
} else {
deferred.resolve(value);
}
}