0
votes

Initially i was getting UnhandledPromiseRejectionWarning: TypeError: Cannot read property "distance" of undefined. to solve that error i have added a if condition with reject. now getting this error UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1). Any solutions ? here is my code

export function fun1(): Promise < survayResult > {
        return new Promise((resolve, reject) => {
            //..........
            //..........
            surveyDistance.forEach((result) => {
                //
            })
            if(condition) {
                reject(new Error("something went erong"));
                return
            }

            let totalDistance = surveyDistance[0].distance;
           // ...
            //...
            resolve("with some data");
        })
    }
1
Sounds like surveyDistance[0] doesn't exist. Not sure what you're trying to do there exactly, but it's more a logic issue than a Promise issue - non-network runtime errors should almost never happenCertainPerformance

1 Answers

0
votes

I think you're over-thinking it, the promise should resolve or reject, they don't have built in error handling support. However in this case the error message is probably a good thing as it is telling you that the arguments (surveyDistance) are not what you expected. I won't comment on good or bad practices because I don't know your code base but you should hesitate to use try/catch unless there really is something that could go wrong (in my experience).

export function fun1(): Promise < survayResult > {
  return new Promise((resolve, reject) => {
    try {
        //..........
        //..........
        surveyDistance.forEach((result) => {
            //
        })
        if(condition) {
            reject(new Error("something went erong"));
            return
        }

        let totalDistance = surveyDistance[0].distance;
       // ...
        //...
        resolve("with some data");
    } catch (e) {
        reject("Your error message:" + e);
    }
  })
}