Using functions with async callback

Question:

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
2
3
4
5
db.users.find({...}).forEach((user) => {
sendSms(user.phone, "A short message", (status) => {
db.smsDeliveries.insert(status);
});
});

Answer:

MongoBooster has a build-in function await (It’s a common js method, not a keyword). It can await a promise or a promise array. Note this await function is different from es7 await, this await function may be used in functions without the async keyword marked.

Please try the following code:

1
2
3
4
5
6
7
8
9
10
11
12
function sendSmsAsync(phone, message){ //promisify sendSms
return new Promise((resolve, reject)=> {
sendSms(phone, message, (status)=>{
resolve(status)
})
});
}

db.users.find({}).forEach((user) => {
let status=await(sendSmsAsync(user.phone, "A short message")); //await a promise
db.smsDeliveries.insert({status});
});

Thank you!

Please visit our feedback page or click the “Feedback” button in the app. Feel free to suggest improvements to our product or service. Users can discuss your suggestion and vote for and against it. We’ll look at it too.