javascriptnode.jses6-promisewhen-js

Moving from when.js to ES6 Promises


I've been using when.js for promises in node.js. I have a function like the following:

function my_func() {
    var d = when.defer();

    // Async actions simulated with timeout
    setTimeout(function() {
        //...
        if(error) {
            return d.resolve(error);
        }
        d.resolve(result);
    }, 1000)

    return d.promise;
}

Which I would call like so:

my_func().then(
    function(res) {
        //...
    },
    function(err) {
        // Handle error
    }
);

How do I do the same thing with ES6 Promises?


Solution

  • Your original function had some mistakes in the if (error) condition, so here's the updated snippet:

    function my_func() {
        var d = when.defer();
    
        // Async actions simulated with timeout
        setTimeout(function() {
            //...
            if(error) {
                d.reject(error);
            }
            d.resolve(result);
        }, 1000)
    
        return d.promise;
    }
    

    which turns into

    function my_func() {
      return new Promise(function (resolve, reject) {
        //Async actions simulated with timeout
        setTimeout(function () {
          //...
          if (error) {
            reject(error);
          }
          resolve(result);
        }, 1000);
      });
    }
    

    This is covered reasonably well in MDN's Promise documentation