How do I handle errors with promises?

后端 未结 2 952
臣服心动
臣服心动 2020-11-29 03:41

As a node programmer. I\'m used to use \"nodebacks\" for handling errors in my code:

myFn(param, function(err, data) {
    if (err){
        //error handling         


        
2条回答
  •  失恋的感觉
    2020-11-29 04:13

    If you're using the async/await syntax, you can just use the regular try-catch syntax for error handling.

    // your promise function
    const myFn = function(param){
      return new Promise(function(resolve, reject){
          if (someLogic()) {
              resolve(someValue);
          } else {
              reject('failure reason');
          }
      });
    }
    
    // Define the parent function as an async function
    async function outerFn(param) {
        try {
            // Wait for the promise to complete using await
            const result = await myFn(param)
            // business logic with result
        } catch (e) {
            //error handling logic
        }
    }
    

提交回复
热议问题