1
votes

I am using async function with IIFE.
But when I run this code by rest api call,
it says

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().

I made try and catch inside of 'for loop'.
How can I make the correct try catch in this case?

(async () => {
        for (let i = 0; i < keywordResult.places.length; i += 1) {
          try {
            const transformKeywordResult = await rp({
              method: 'GET',
              uri:
                '',
              qs: {
                query: query
              },
              json: true
            });

            let addrInfo = transformKeywordResult.addresses[i];
            if (!addrInfo.addressElements[8].longName) {
              addrInfo.addressElements[8].longName = '';
            }

            searchResult.push(transformKeywordResult);
          } catch (error) {
            return res.status(200).json({
              success: false,
              code: 500,
              msg: 'Internal Server Error',
              err: error,
              pos: 0
            });
          }
        }

        return res.send(searchResult);
      })();
2
What exactly throws in that code? The await should be caught properlyCertainPerformance
Your query is the same in each loop iteration. Why not grab it once and iterate over the data instead?Andy

2 Answers

0
votes

Try closing the for loop in the try block, because if any error occurs outside the try block, there is no catch block to hold the error.

( async () => {

    try {
        for ( let i = 0; i < keywordResult.places.length; i += 1 ) {
            const transformKeywordResult = await rp( {
                method: 'GET',
                uri: '',
                qs: {
                    query: query
                },
                json: true
            } );

            let addrInfo = transformKeywordResult.addresses[ i ];
            if ( !addrInfo.addressElements[ 8 ].longName ) {
                addrInfo.addressElements[ 8 ].longName = '';
            }
            searchResult.push( transformKeywordResult );
        }
        return res.send( searchResult );
    } catch ( error ) {
        return res.status( 200 ).json( {
            success: false,
            code: 500,
            msg: 'Internal Server Error',
            err: error,
            pos: 0
        } );
    }

} )();
0
votes

Your rps are caught properly, but there's one promise left without apparent error catching, and that's your IIFE:

(async () => {
// do some stuff, including async
)();

It can, BTW, throw its own errors (independent of async API errors), for example when addrInfo.addressElements comes shorter than 9 elements long.

Try

(async () => {
// do some stuff, including async
)().catch(/* throw some error logic handling here, or even just noop */);