0

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?

Sean Lynch
  • 2,852
  • 4
  • 32
  • 46

3 Answers3

2

The structure is fairly similar:

function my_func() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            if (error) {
                reject('no');
            }
            resolve('yes')
        }, 1000);
    });
}
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
2

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

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
1
//Creating promise
 function my_func() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
        //...
        if(error) {
           reject(Error("Error Message"));
        }
        resolve("Success message")
    }, 1000)
    });
}
//Using it
my_func().then(function(response){
    console.log("Success!", response);
}, function(err){
    console.error("Failed!", err);
})
Raja Sekar
  • 2,062
  • 16
  • 23