Subramanian Vignesh
Subramanian Vignesh

Reputation: 217

Strange behaviour in javascript Promise

Considering code snippet below,

function one(){
    var prm = new Promise(function(resolve,reject){

    });
    prm.customKey = function(){
    }
    return prm;
}
function two(){
    return one().then(function(){
        //something
    });
}

Now calling the function two, returns a promise in which 'customKey' is missing

function three(){
    return one();
}  

But while doing the same thing in function three(without handling success using 'then'), returns a promise which has 'customKey' in it.

Can someone clarify me whats really happening and why?

Upvotes: 0

Views: 69

Answers (1)

aprogrammer
aprogrammer

Reputation: 1774

As you can see from "Mozilla Docs" then method returns new Promise (e.g: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then).

If you want to assign a function to retrieve / do something in resolve function do it like this:

var prm = new Promise((resolve, reject) => {
    let customKeyFunction = () => {
        console.log("I'm custom key function.");
    };

    resolve(customKeyFunction);
})

From now on you can call this function like that:

function two() {
    return one().then(customKey => {
        customKey();
    })
}

Upvotes: 3

Related Questions