Обещания JS - Почему я вижу предупреждение UnhandledPromiseRejection и DeprecationWarning? - PullRequest
0 голосов
/ 27 апреля 2018

Я разбираюсь с обещаниями и их настройкой, однако не могу понять, почему узел считает, что мое обещание не обрабатывается, когда речь идет об ошибках ... Может кто-нибудь объяснить, пожалуйста?

Мой простой код

    // Setting up the Promise
    function add(x, y) {
        return new Promise((response, reject) => {
            // Simple conditional (not perfect, but it just proves a point)
            if(x !== null && y !== null) {
                // I know I could have done 'response(x + y)', but I wanted 
                // to console.log the result also
                var calc = x + y
                response(calc)
                console.log('Calculation: ' + x + ' + ' + y + ' = ' + calc)
            } else {
                // My console does not throw this error?
                reject('One of the inputs was null')
            }
        })
    }
    
    // Function using the Promise
    function calc() {
        add(1, 3)
            .then(res => add(res, 3))
            .then(res => add(res, null))
            .then(res => console.log('Final result: '+res))
            .catch(err => {
                // This error is thrown in console
                throw new Error('Something went horribly wrong')
            })
    }
    
    // Run the code
    calc();

Обновление

Первоначально я отправил «отклонить» с выданной ошибкой, которую, как я понимаю, нужно поймать.

Я также хочу понять, почему строка в 'reject' не видна в моей консоли?

Выход на консоль:

Calculation: 1 + 3 = 4
Calculation: 4 + 3 = 7
(node:61950) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Something went horribly wrong
(node:61950) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Ответы [ 2 ]

0 голосов
/ 27 апреля 2018

Вы звоните reject и , выдавая ошибку. Вам нужно сделать только один из них.

Вы не отображаете первое сообщение об ошибке.

Также важно использовать .catch для любой сгенерированной ошибки при вызове add.

Когда вы делаете это: throw new Error('Something went horribly wrong') вы все еще находитесь в promise, и если вы не поймаете его, у вас будут проблемы. В будущих версиях Node.js это приведет к завершению работы вашего приложения с кодом ошибки. Таким образом, вам нужно быть уверенным, что вы всегда обнаруживаете сбои в обещании.

Использование отклонения

// Setting up the Promise
function add(x, y) {
  return new Promise((response, reject) => {
    // Simple conditional (not perfect, but it just proves a point)
    if(x !== null && y !== null) {
      // I know I could have done 'response(x + y)', but I wanted 
      // to console.log the result also
      var calc = x + y
      response(calc)
      console.log('Calculation: ' + x + ' + ' + y + ' = ' + calc)
    } else {
      // My console does not throw this error?
      reject(new Error('One of the inputs was null'))
    }
  })
}

// Function using the Promise
function calc() {
  return add(1, 3)
    .then(res => add(res, 3))
    .then(res => add(res, null))
    .then(res => console.log('Final result: '+res))
    .catch(err => {
      console.error("Internal Error:", err.message);
      // This error is thrown in console
      throw new Error('Something went horribly wrong')
    })
}

// Run the code
calc().catch((err) => {
  console.error("Outer error:", err.message);
});

Использование броска:

// Setting up the Promise
function add(x, y) {
  return new Promise((response, reject) => {
    // Simple conditional (not perfect, but it just proves a point)
    if(x !== null && y !== null) {
      // I know I could have done 'response(x + y)', but I wanted 
      // to console.log the result also
      var calc = x + y
      response(calc)
      console.log('Calculation: ' + x + ' + ' + y + ' = ' + calc)
    } else {
      // My console does not throw this error?
      throw new Error('One of the inputs was null')
    }
  })
}

// Function using the Promise
function calc() {
  return add(1, 3)
    .then(res => add(res, 3))
    .then(res => add(res, null))
    .then(res => console.log('Final result: '+res))
    .catch(err => {
      console.error("Internal Error:", err.message);
      // This error is thrown in console
      throw new Error('Something went horribly wrong')
    })
}

// Run the code
calc().catch((err) => {
  console.error("Outer error:", err.message);
});

Я добавил return обещания, возвращенного add, чтобы вы могли catch окончательную ошибку.

Другой способ сделать это - не выдавать окончательную ошибку и обрабатывать ее по-другому.

0 голосов
/ 27 апреля 2018

В вашей функции, используя Обещание:

// Function using the Promise
function calc() {
    add(1, 3)
        .then(res => add(res, 3))
        .then(res => add(res, null))
        .then(res => console.log('Final result: '+res))
        .catch(err => {
            // This error is thrown in console
    --->    throw new Error('Something went horribly wrong')
        })
}

Строка, помеченная --->, выдает ошибку. Эта ошибка не обнаружена. Обычно, когда вы ловите ошибку, вы хотите что-то с ней сделать. Если вы отбрасываете его назад или выкидываете другую ошибку, этот бросок должен быть пойман.

Я бы сделал следующее:

// Function using the Promise
function calc() {
    return add(1, 3)
        .then(res => add(res, 3))
        .then(res => add(res, null))
        .then(res => console.log('Final result: '+res))
        .catch(err => {
            // This error is thrown in console
            throw new Error('Something went horribly wrong')
        })
}

calc().catch(err => {
    console.log(error.message); // For example
});
...