خرید بک لینک

Vote count: 0

I'm struggling to figure out how to properly bubble errors with promises.

Specifically, what I'm talking about is a situation where there is nested promises. I want to be able to implictly pass the resolve and reject functions to the nested promise.

It'll be more obvious what I mean by showing some code.

The following is what I have been using successfully:

var asyncIsEven = function(number) {
  retu new Promise(function(resolve, reject){
      if (number % 2 == 0) { retu resolve(number) }
      else { retu reject("number is odd") }
  })
}

var A = function (number) {
  retu new Promise(function(resolve, reject){
    retu asyncIsEven(number).then(resolve).catch(reject)
  })
}

Here, it seems pretty uecessary to write then(resolve).catch(reject).

I am looking for ways to avoid writing this.

What I've tried:

this works, but is not really what I want

var A = function (number) {
  retu Promise.all([asyncIsEven(number)])
}

This is what I want to write, but it doesn't work

var A = function(number) {
  retu new Promise(function(resolve, reject) {
    retu asyncIsEven(number).then(resolve)
  })
}

When I say it "doesnt work", what I mean is that I caot write the following:

A(2).then(function(number) {
  console.log(`${number} is even`)
}).catch(function(err) {
  console.log(err)
})

Because the catch function will never be called.

In other words - if I define function A to retu asyncIsEven(number).then(resolve), how can I bubble errors from asyncIsEven up to the reject callback given to A?

asked 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: چهارشنبه 19 خرداد 1395 ساعت: 7:55

صفحه بندی