Using functions with async callback

Christian Lindgren shared this problem 7 years ago
Solved

Hi,


Problem:

We're having a situation where we want to call a function with an async callback.

The issue that arises is that the script thread terminates before the callback is executed.

Is there any way to prevent the script thread from terminating before we get the callback?


Background:

We're intending to read a collection containing phone numbers, call Twilio Api (an sms service) to send a message, and finally store the status from Twilio into another collection.


  1. db.users.find({...}).forEach((user) => {
  2. sendSms(user.phone, "A short message", (status) => {
  3. db.smsDeliveries.insert(status);
  4. });
  5. });


Immensely thankfull for any kind of help, input or suggestion that can make us able to achieve this.


PS! This task is an ad-hoc task in our work flow, otherwise we would have done this as part of our application.


Best regards,

Christian

Best Answer
photo

Hi,

Thank you for your feedback.

MongoBooster has a build-in function await. It can await a promise or a promise array.


Please try the following code:


  1. let birdPromise=require('bluebird');
  2. function sendSmsAsync(phone, message){ //promiseify sendSms
  3. return new birdPromise(function (resolve, reject) {
  4. sendSms(phone, message, (status)=>{
  5. resolve(status)
  6. })
  7. });
  8. }
  9. db.users.find({}).forEach((user) => {
  10. let status=await(sendSmsAsync(user.phone, "A short message")); //await a promise
  11. db.smsDeliveries.insert({status});
  12. });

Replies (2)

photo
3

Hi,

Thank you for your feedback.

MongoBooster has a build-in function await. It can await a promise or a promise array.


Please try the following code:


  1. let birdPromise=require('bluebird');
  2. function sendSmsAsync(phone, message){ //promiseify sendSms
  3. return new birdPromise(function (resolve, reject) {
  4. sendSms(phone, message, (status)=>{
  5. resolve(status)
  6. })
  7. });
  8. }
  9. db.users.find({}).forEach((user) => {
  10. let status=await(sendSmsAsync(user.phone, "A short message")); //await a promise
  11. db.smsDeliveries.insert({status});
  12. });

photo
1

That was exactly what I was looking for!


Thank you for saving the day ;)

Best regards,

Christian

Leave a Comment
 
Attach a file