Promise 数据和异常处理

问题描述

我对 promise 的使用感到困惑,特别是它的数据操作方式(从块到块传递值)和异常处理(冒泡错误)。我正在尝试学习使用承诺和处理错误的正确方法,例如

Error: A caught error.
    at promiseTwo()
    at promiSEOne()
    at subprocess()
    at mainprocess()

这是我实现它们的两次尝试:

尝试 1:笨拙,嵌套很深,并且错误未被发现。

var subprocess = () => {
    return new Promise((resolve,reject) => {
        promiSEOne().then(data1 => {
            // Some code with data1,throw some error
            promiseTwo().then(data2 => {
                // Some code with data1n2,throw some error
                promiseThree().then(data3 => {
                    // Data manipulation with data1,data2,and data3
                    return resolve(<...>)
                }).catch(err3 => { throw err3 })
            }.catch(err2n3 => { throw err2n3 })          // >>> ERR: Cannot get err3.
        }.catch(err1n2n3 => { return reject(err1n2n3) }) // >>> ERR: Cannot get err3 or err2.
    }
}

return new Promise((resolve,reject) => {
    subprocess().then(data => {
        // Todo
    }).catch(allErr => { return reject(allErr) }
}

尝试 2: 无法使用上一个承诺块中的数据。

var subprocess = () => {
    return new Promise((resolve,reject) => {
        promiSEOne()
        .then(data1 => {
            // Some code with data1,throw some error
            return promiseTwo()
        })
        .then(data2 => {
            // Some code with data1n2,throw some error
            // >>> ERR: Cannot get data1
            return promiseThree()
        })
        .then(data3 => {
            // Data manipulation with data1,and data3
            // >>> ERR: Cannot get data1 and data2
            return resolve(<...>)
        })
        .catch(err1n2n3 => { 
            return reject(err1n2n3) 
        })
    }
}

return new Promise((resolve,reject) => {
    subprocess().then(data => {
        // Some code,throw some error
    }).catch(allErr => { return reject(allErr) }
}

注意: 一些 promise 块(即 promiSEOnepromiseTwo 等)是预定义的,因此我无法控制它们将返回哪些数据.我确信尝试中存在更多错误(例如,如果return调用函数是正确的方法)。

请帮忙。谢谢。

解决方法

对于这种情况,您可以将 promise 和 async-await 结合在一起。

从问题来看,我们似乎有三个 promise 和一个执行和处理它们的函数。

你可以试试这样的 -

const subProcess = () => {
  return new Promise((resolve,reject) => {
    // Using IIFE ( You shouldn't put async keyword on promise callbac )
    (async () => {
      // Use of try catch to handle the errors
      try { 
        await promiseOne()
        await promiseTwo()
        await promiseThree()
        // Additional code if need after them
      } catch(err){
        // Handle error ( all three promise error will be transferred here )
      }
    })()

  })
}

上面的代码等待 Promise 一一执行,如果有的话,也会从所有三个 Promise 中捕获错误。

正如@samuei 提到的,你也可以在这个中使用 Promise.all()。

const subProcess = () => {
  return new Promise((resolve,reject) => {
    // Using IIFE ( You shouldn't put async keyword on promise callbac )
    (async () => {
      // Use of try catch to handle the errors
      try { 
        const myPromises = [promiseOne,promiseTwo,promiseThree];
        const res = await Promise.all(myPromises);
        // Additional code if need after them
      } catch(err){
        // Handle error ( all three promise error will be transferred here )
      }
    })()

  })
}

如果你不想使用 async-await 那么你也可以这样做

const subProcess = () => {
  return new Promise((resolve,reject) => {
    const myPromises = [];
    const myPromises = [promiseOne,promiseThree];

    Promise.all(myPromises)
    .then(res => {
      // Handle the response
    })
    .catch(err => {
      // Handle the error
    })

  })
}
,

听起来您正在寻找 Promise.all,它可以让您设置一系列的 Promise,然后在它们全部解决后处理结果。