Is it possible to catch exceptions thrown in a JavaScript async callback?

前端 未结 7 1210
春和景丽
春和景丽 2020-11-27 04:15

Is there a way to catch exceptions in JavaScript callbacks? Is it even possible?

Uncaught Error: Invalid value for property 

7条回答
  •  攒了一身酷
    2020-11-27 04:47

    If you can use Promises and async/await, it can be solved as shown in sample code below:

    async function geocode(zipcode) {
    
      return new Promise((resolve, reject) => {
    
        const g = new google.maps.Geocoder().geocode({ 'address': zipcode },  function(geoResult, geoStatus) {
          if (geoStatus != google.maps.GeocoderStatus.OK) {
            reject(new Error("Callback Exception caught"));
          } else {
            resolve(g);
          };
    
        });
      });
    }
    
    try {
      // ...
    
      // g will be an instance of new google.maps.Geocoder().geocode..
      // you can resolve with desired variables
      const g = await geocode(zipcode);
    
      // ...
    } catch( e ) {
      console.log(e);
    }
    

提交回复
热议问题