-1

I'm fairly new to Javascript, and I need help with making my code wait for functions to finish before moving on to the next. In my code, I'm sending an email using SES, and I'm publishing a topic within SNS.

After sending the email and publishing the topic, I need to navigate the user to a thank you page.

With how I have my code setup, it's very inconsistent. Sometimes it will send the the email and publish before navigating, and sometimes it will do one or the other then navigate. I need help with understanding how to make the code wait for those two functions to finish before navigating to a different page.

Thank you all in advance!

I've tried using an if statement, but it didn't work out as I thought.

sns.publish(snsParams, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});
ses.sendEmail(sesParams, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});
window.location = 'https://abc123.com/contact/thanks/';
Sunit Gautam
  • 5,495
  • 2
  • 18
  • 31
Kane
  • 15
  • 3

1 Answers1

0

You can do that either by using the second call as a callback to the first one or by promisifying the calls:

sns.publish(snsParams, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
}).promise().then(() => {
    return ses.sendEmail(sesParams, function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else     console.log(data);           // successful response
}).promise().then(() => window.location = 'https://abc123.com/contact/thanks/'));
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • Wouldn't `Promise.all` be better? You can also omit the callback if you're using Promises, if you want, it doesn't serve much purpose – CertainPerformance Jun 18 '19 at 16:00
  • @CertainPerformance if you want to redirect only after both actions took place successfully and you don't care about the order in which the actions were executed you can indeed use `Promise.all`. All that said, I wouldn't do things like sns/ses actions from the frontend - better call your backend and do it there! – Nir Alfasi Jun 18 '19 at 16:09
  • @alfasin I tried this out, but it doesn't work. After publishing, it navigates directly to the new page. It doesn't send the email from SES. Any ideas? Also, I don't care what order the two functions are executed in, so I think I will look into Promise.all. – Kane Jun 18 '19 at 16:23