Search code examples
javascriptes6-promise

Can a promise be used on any returning function in javascript?


I usually see usage of npm library objects. They are typical functions with variable assignments. But usually on some functions I discover a promise could be used?

Does this mean a promise typically can be called on any returning function?


Solution

  • Nope,

    Promise VS defer Object

    defer Object is regular object with promise property to create defer object just call

    var defer = Pormise.defer();
    console.log(defer.promise);
    

    any defer Object must has resolve and reject properties

    defer.promise object has status property and returned data property

    To convert any function to Promise Object you can wrap it with this

    var promiseFunction = new Promise(function(resolve,reject){
       var result = anyFunction();
       if(result)
        resolve(result);
       else
        reject("Error")
    });
    

    To Use this

    promiseFunction.then(function(result){
    
    }).catch(function(error){
    
    })