← Back To API Reference

.asCallback

.asCallback(
    [function(any error, any value) callback],
    [Object {spread: boolean=false} options]
) -> this
.nodeify(
    [function(any error, any value) callback],
    [Object {spread: boolean=false} options]
) -> this

Register a node-style callback on this promise. When this promise is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be null in case of success.

Returns back this promise instead of creating a new one. If the callback argument is not a function, this method does not do anything.

This can be used to create APIs that both accept node-style callbacks and return promises:

function getDataFor(input, callback) {
    return dataFromDataBase(input).asCallback(callback);
}

The above function can then make everyone happy.

Promises:

getDataFor("me").then(function(dataForMe) {
    console.log(dataForMe);
});

Normal callbacks:

getDataFor("me", function(err, dataForMe) {
    if( err ) {
        console.error( err );
    }
    console.log(dataForMe);
});

Promises can be rejected with falsy values (or no value at all, equal to rejecting with undefined), however .asCallback will call the callback with an Error object if the promise's rejection reason is a falsy value. You can retrieve the original falsy value from the error's .cause property.

Example:

Promise.reject(null).asCallback(function(err, result) {
    // If is executed
    if (err) {
        // Logs 'null'
        console.log(err.cause);
    }
});

There is no effect on performance if the user doesn't actually pass a node-style callback function.

Option: spread

Some nodebacks expect more than 1 success value but there is no mapping for this in the promise world. You may specify the option spread to call the nodeback with multiple values when the fulfillment value is an array:

Promise.resolve([1,2,3]).asCallback(function(err, result) {
    // err == null
    // result is the array [1,2,3]
});

Promise.resolve([1,2,3]).asCallback(function(err, a, b, c) {
    // err == null
    // a == 1
    // b == 2
    // c == 3
}, {spread: true});

Promise.resolve(123).asCallback(function(err, a, b, c) {
    // err == null
    // a == 123
    // b == undefined
    // c == undefined
}, {spread: true});