0

I am new to Node.js programming. I came to know about promise object. But one of my colleagues faced an interview question.

  1. Without using any third party promise libraries which are available in npm(example Promise, bluebird), I need to implement a promise function which returns then() and catch() function like below.

    asyncPromise().then().catch()

For example:

function asyncFunction(cb){
    //-----------
    cb(err,data);
}

function asyncPromise(){
}

We need to Wrap a function around that function that it will make it behave as a promise. How can we achieve this with both of above functions, without using the third party libraries?

Mohan Raja
  • 129
  • 1
  • 13

1 Answers1

0

Promises are built into node and the latest versions of node have implemented support for async/await functions. Here are two ways you could do what they want. I prefer the second method.

function asyncFunc(){
    return new Promise((resolve, reject) => { 
        if(someError){
            // triggers .catch callback
            return reject('There was an error');
        }
        // triggers .then callback
        return resolve();
    });
}

asyncFunc.then(() => { /* do something */ }).catch(e => { // do something });

Using async/await

function asyncFunc(){
    return new Promise((resolve, reject) => { resolve() });
}

async function caller(){
    let dataFromPromise;
    try{
        dataFromPromise = await asyncFunc();
    } catch(e){
        // do something with error
    }
    // do something with dataFromPromise
}
pizzarob
  • 11,711
  • 6
  • 48
  • 69