AWS Lambda promise with callback issue









up vote
0
down vote

favorite












I am using mail-confirm to validate an email address and the Lambda function is returning rather than waiting for the promise result on




email.check().then(results=>




And jumps straight to




console.log('callback issue');




and returns. I would expect the email check to finish and return the results object inside of the callback. Instead the function is returned before the promise can resolve. Any pointers will be appreciated.



Function example:



const MailConfirm = require('mail-confirm');
const isemail = require('isemail');

module.exports.app = async (event, context) =>
let request = JSON.parse(event.body)


if(request.email)
var emailToValidate = request.email
if(isemail.validate(emailToValidate))
console.log(`$emailToValidate - stage 1 pass`);

const email = new MailConfirm(
emailAddress: emailToValidate,
timeout: 2000,
invalidMailboxKeywords: ['noreply', 'noemail']
);

//Promise issue
email.check().then(results=>
console.log(results);
return
statusCode: 200,
body: JSON.stringify(
validatedEmail: emailToValidate,
isValid: true,
),
;
).catch(err=>
console.log(`$emailToValidate stage 2/3 failed`)
return
statusCode: 200,
body: JSON.stringify(
validatedEmail: emailToValidate,
isValid: false,
message: err,
),
;
);
//Returns here
console.log('callback issue');
else
return
statusCode: 200,
body: JSON.stringify(
validatedEmail: emailToValidate,
isValid: false,
message: 'Failed stage 1 validation',
),
;



// return
// statusCode: 500,
// body: JSON.stringify(
// message: 'Something went wrong.',
// ),
// ;
;


EDIT:



Thanks everyone for your responses. I have implemented the await and it is working nicely when testing




test@gmail.com




. However if i validate




test@email.com




the email.check() function doesn't return and my lambda function returns with a blank response (502 to API gateway). I am no sure what happens after let results = await email.check(); when validating test@email.com. My Lambada function is not timing out.



 try
let results = await email.check();
console.log(results);
//Returns ok on test@gmail.com
return
statusCode: 200,
body: JSON.stringify(
validatedEmail: emailToValidate,
isValid: true,
),
;
catch(err)
console.log(`$emailToValidate stage 2/3 failed`)
return
statusCode: 200,
body: JSON.stringify(
validatedEmail: emailToValidate,
isValid: false,
message: err,
),
;



Lambda logs

START Version: $LATEST
test@email.com - stage 1 pass
END
REPORT Duration: 647.88 ms Billed Duration: 700 ms Memory Size: 128 MB Max Memory Used: 21 MB



API Gateway 502 Bad Gateway (Due to the Lambda function response being null)


"message": "Internal server error"


EDIT 2:



It turns out i am getting a 554 error in mail-confirm when validating test@email.com.










share


In short you dont await somePromise.then you just await the promise.



If you want to save yourself a whole world of hurt switch to Node 8.10 you can use most of the latest ES6 features, just make sure you use:



const someLib = require('whatever)


rather than import!






share|improve this answer












You need to do some reading but basically anything in a async function that returns a promise you can await like so



module.exports.app = async (event, context, callback) => 
try
const results = await SomeClass.somePromise()

const anotherResult = await SomeOtherClass.somePromise()

// do some stuff

callback(null, some_valid_http_response)


catch (e) [

callback(e, null) // or handle another way

}


In short you dont await somePromise.then you just await the promise.



If you want to save yourself a whole world of hurt switch to Node 8.10 you can use most of the latest ES6 features, just make sure you use:



const someLib = require('whatever)


rather than import!







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 11 at 20:49









Mrk Fldig

2,23841645




2,23841645






















      up vote
      0
      down vote













      Your function is async, email.check().then(...) returns a promise which is never awaited on your side. Remove async at your lambda handler or await await email.check().then(...) the returned promise. If you remove async you have to use the callback property of lambda.






      share|improve this answer


























        up vote
        0
        down vote













        Your function is async, email.check().then(...) returns a promise which is never awaited on your side. Remove async at your lambda handler or await await email.check().then(...) the returned promise. If you remove async you have to use the callback property of lambda.






        share|improve this answer
























          up vote
          0
          down vote










          up vote
          0
          down vote









          Your function is async, email.check().then(...) returns a promise which is never awaited on your side. Remove async at your lambda handler or await await email.check().then(...) the returned promise. If you remove async you have to use the callback property of lambda.






          share|improve this answer














          Your function is async, email.check().then(...) returns a promise which is never awaited on your side. Remove async at your lambda handler or await await email.check().then(...) the returned promise. If you remove async you have to use the callback property of lambda.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 10 at 16:22

























          answered Nov 10 at 16:05









          smartinspereira

          13




          13




















              up vote
              0
              down vote













              Any method that is "thenable" is considered a Promise and will execute asynchronously. Therefore, email.check() is being invoked as a Promise and will not block code execution, which results in console.log() being invoked before you get a response. Since you're already using async/await in your lambda handler, you can just await for the response from email.check() before continuing.



              let resp = await email.check().then(results=>
              console.log(results);
              return
              statusCode: 200,
              body: JSON.stringify(
              validatedEmail: emailToValidate,
              isValid: true,
              ),
              ;
              )

              console.log( resp ); // outputs object returned from email.check()





              share|improve this answer




















              • Await and then doesn't really make sense buddy.
                – Mrk Fldig
                Nov 11 at 20:44










              • @MrkFldig async/await returns a Promise, which means it is thenable. After all, it is simply just a wrapper around native Promises and they can be used together with no issues. Give it a try.
                – putipong
                Nov 12 at 19:18











              • Simply put I'd reject any PR that used await somePromise.then() it's almost an antipattern. There are reasons for doing it, for example mysql lib returns (err, results) but you can still wrap that in a function to return the right object.
                – Mrk Fldig
                Nov 12 at 19:23














              up vote
              0
              down vote













              Any method that is "thenable" is considered a Promise and will execute asynchronously. Therefore, email.check() is being invoked as a Promise and will not block code execution, which results in console.log() being invoked before you get a response. Since you're already using async/await in your lambda handler, you can just await for the response from email.check() before continuing.



              let resp = await email.check().then(results=>
              console.log(results);
              return
              statusCode: 200,
              body: JSON.stringify(
              validatedEmail: emailToValidate,
              isValid: true,
              ),
              ;
              )

              console.log( resp ); // outputs object returned from email.check()





              share|improve this answer




















              • Await and then doesn't really make sense buddy.
                – Mrk Fldig
                Nov 11 at 20:44










              • @MrkFldig async/await returns a Promise, which means it is thenable. After all, it is simply just a wrapper around native Promises and they can be used together with no issues. Give it a try.
                – putipong
                Nov 12 at 19:18











              • Simply put I'd reject any PR that used await somePromise.then() it's almost an antipattern. There are reasons for doing it, for example mysql lib returns (err, results) but you can still wrap that in a function to return the right object.
                – Mrk Fldig
                Nov 12 at 19:23












              up vote
              0
              down vote










              up vote
              0
              down vote









              Any method that is "thenable" is considered a Promise and will execute asynchronously. Therefore, email.check() is being invoked as a Promise and will not block code execution, which results in console.log() being invoked before you get a response. Since you're already using async/await in your lambda handler, you can just await for the response from email.check() before continuing.



              let resp = await email.check().then(results=>
              console.log(results);
              return
              statusCode: 200,
              body: JSON.stringify(
              validatedEmail: emailToValidate,
              isValid: true,
              ),
              ;
              )

              console.log( resp ); // outputs object returned from email.check()





              share|improve this answer












              Any method that is "thenable" is considered a Promise and will execute asynchronously. Therefore, email.check() is being invoked as a Promise and will not block code execution, which results in console.log() being invoked before you get a response. Since you're already using async/await in your lambda handler, you can just await for the response from email.check() before continuing.



              let resp = await email.check().then(results=>
              console.log(results);
              return
              statusCode: 200,
              body: JSON.stringify(
              validatedEmail: emailToValidate,
              isValid: true,
              ),
              ;
              )

              console.log( resp ); // outputs object returned from email.check()






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 10 at 16:51









              putipong

              1809




              1809











              • Await and then doesn't really make sense buddy.
                – Mrk Fldig
                Nov 11 at 20:44










              • @MrkFldig async/await returns a Promise, which means it is thenable. After all, it is simply just a wrapper around native Promises and they can be used together with no issues. Give it a try.
                – putipong
                Nov 12 at 19:18











              • Simply put I'd reject any PR that used await somePromise.then() it's almost an antipattern. There are reasons for doing it, for example mysql lib returns (err, results) but you can still wrap that in a function to return the right object.
                – Mrk Fldig
                Nov 12 at 19:23
















              • Await and then doesn't really make sense buddy.
                – Mrk Fldig
                Nov 11 at 20:44










              • @MrkFldig async/await returns a Promise, which means it is thenable. After all, it is simply just a wrapper around native Promises and they can be used together with no issues. Give it a try.
                – putipong
                Nov 12 at 19:18











              • Simply put I'd reject any PR that used await somePromise.then() it's almost an antipattern. There are reasons for doing it, for example mysql lib returns (err, results) but you can still wrap that in a function to return the right object.
                – Mrk Fldig
                Nov 12 at 19:23















              Await and then doesn't really make sense buddy.
              – Mrk Fldig
              Nov 11 at 20:44




              Await and then doesn't really make sense buddy.
              – Mrk Fldig
              Nov 11 at 20:44












              @MrkFldig async/await returns a Promise, which means it is thenable. After all, it is simply just a wrapper around native Promises and they can be used together with no issues. Give it a try.
              – putipong
              Nov 12 at 19:18





              @MrkFldig async/await returns a Promise, which means it is thenable. After all, it is simply just a wrapper around native Promises and they can be used together with no issues. Give it a try.
              – putipong
              Nov 12 at 19:18













              Simply put I'd reject any PR that used await somePromise.then() it's almost an antipattern. There are reasons for doing it, for example mysql lib returns (err, results) but you can still wrap that in a function to return the right object.
              – Mrk Fldig
              Nov 12 at 19:23




              Simply put I'd reject any PR that used await somePromise.then() it's almost an antipattern. There are reasons for doing it, for example mysql lib returns (err, results) but you can still wrap that in a function to return the right object.
              – Mrk Fldig
              Nov 12 at 19:23

















              draft saved

              draft discarded
















































              Thanks for contributing an answer to Stack Overflow!


              • Please be sure to answer the question. Provide details and share your research!

              But avoid


              • Asking for help, clarification, or responding to other answers.

              • Making statements based on opinion; back them up with references or personal experience.

              To learn more, see our tips on writing great answers.





              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


              Please pay close attention to the following guidance:


              • Please be sure to answer the question. Provide details and share your research!

              But avoid


              • Asking for help, clarification, or responding to other answers.

              • Making statements based on opinion; back them up with references or personal experience.

              To learn more, see our tips on writing great answers.




              draft saved


              draft discarded














              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236315%2faws-lambda-promise-with-callback-issue%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown





















































              Required, but never shown














              Required, but never shown












              Required, but never shown







              Required, but never shown

































              Required, but never shown














              Required, but never shown












              Required, but never shown







              Required, but never shown







              Popular posts from this blog

              Darth Vader #20

              How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

              Ondo