Test1 Test2
Test1 Test2

Reputation: 327

Transforming callbacks into promises with multiple arguments

I have successfully wrapped the function "notMyFunction" in a promise so I can use "notMyFunction" as if it were a promise. Like so:

// I do not have access to "notMyFunction"
function notMyFunction(a, cb) {
    if (a === 'latest') {
        cb('123');
    } else {
        cb('error');
    }
}

// changing callback into a promise
function deploy(someVariable) {
    return new Promise((resolve, reject) => {
        notMyFunction(someVariable, resolve);
    });
}

// using callback as if it were a promise
deploy('latest').then((time) => {
    console.log(time)
}, (err) => {
    console.log(err)
})

My question is: How do I do the same thing, when "notMyFunction" actually passes two arguments to the callback like so:

function notMyFunction(a, cb) {
    if (a === 'latest') {
        cb(null, '123');
    } else {
        cb('error', null);
    }
}
function deploy(someVariable) {
    return new Promise((resolve, reject) => {
        notMyFunction(someVariable, resolve);
    });
}
deploy('latest').then((time) => {
    // I need access to 123, not null
    console.log(time)
}, (err) => {
    console.log(err)
})

Upvotes: 1

Views: 637

Answers (2)

acdcjunior
acdcjunior

Reputation: 135752

Your promises are not handling error well. There will never be a .catch() since you are never calling reject().

If believe what you really want is something along the lines of:

function deploy(someVariable) {
    return new Promise((resolve, reject) => {
        notMyFunction(someVariable, (firstArg, ...otherArgs) => {

            // assuming that, on errors, your first argument is 'error'
            if (firstArg === 'error') {                         
                reject([firstArg, ...otherArgs]);
            } else {
                resolve([firstArg, ...otherArgs]);
            }
        });
    });
}

Upvotes: 0

Chris Jaynes
Chris Jaynes

Reputation: 2907

I think you might want to look into the concept of "promisification".

Newer versions of Node.js have a util.promisify function that can handle this. Dr. Axel has a great write-up on util.promisify.

If you're in the browser, you may want to consider pulling in a Promisify polyfill/shim like es6-promisify.

Having a consistent way to promisify functions across your codebase will help you to avoid a lot of potential problems.

Upvotes: 1

Related Questions