简体   繁体   中英

Async Await & Promise Explanation

I am bit confused with the following code. When the promise returns we use .then & .catch but in this code it's not there. It would be great if someone can explain it to me.

Another thing is, when there is a connection error from mongo db then the highlighted code ( "// highlighted 1 //" ) throws the error and then returns back to server.post async version in the catch section ( " // highlighted 2 // " ). But error is undefined. Why ?

That why I have used the error !== undefined? error : ''; error !== undefined? error : ''; statement

Please guide me

I have converted this promise based to async await. They are working fine. This endpoint is for reporting of user calls.

----- Async version

server.post('/reporting_in', async (request, response) => {
    if (reporter.IsReportingOn()) {
        let message = request.body;
        try {
            const msg = await reporter.addLogMessage(message, response);
            response.send(200,{"status": "success"});
        } catch (error) {
            log.error("\n Error logging call details into database : 
\n\n", error!==undefined?error:'', "\n\n"); // highlighted 2 //
            response.send(503, {error: 'Unable to connect db'});
        }
    } else {
        response.send(503, 'Reporting is not enabled');
    }
});

--- Promise Version

server.post('/reporting_in', async (request, response) => {
    if (reporter.IsReportingOn()) {
         return new Promise((resolve, reject) => {
             let message = request.body;
             try {
                 reporter.addLogMessage(message, response);
                 resolve(response.send(200));
             } catch (error) {
                 reject(log.error("\n Error logging call details 
into database : \n\n", error, "\n\n"));
        //     }
        // });
    } else {
        response.send(503, 'Reporting is not enabled');
    }
  });

---> This function is in reporting.js file

let addLogMessage = async message => {
  let client;
  try {
    client = await MongoClient.connect(url, {
      useNewUrlParser: true
    });
  } catch (error) {
    throw (log.error(error)); // highlighted 1 //
  }

  try {
    let db = client.db('reporting');
    const res = await db.collection('reports').insertOne(message);
    log.info("\n Succcessfully logged reporting data into the 
database : \n\n");
  } catch (error) {
     log.error("\nError in logging reporting event : \n\n", 
error.stack, "\n\n")
  } finally {
     client.close();
  }

 }

async and await are used to handle the async operation in JavaScript.whether the promises are resolved or reject it can be handled via then or catch.

return new Promise((resolve,reject)=>{
//do some task
//if successfull
resolve('done')
//otherwise
reject('unsuccessfull')
});

and to handle the promise we use async wait with try and catch

try{
  const response = await promise;
}catch(e){
 //handle the error
}

Note : await can only be used with async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM