Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - Async wait for a function

I'm trying to send an SMS for a function. But the problem is: The function takes about 10-15 seconds to finish (Since we do bunch of stuff with PhantomJS).

_.each(users, function(userData){ // This does not work since i need to wait for 15 seconds
  smsFree.sendSMSFree(userData, productUrl);
});

I've even tried using setTimeout but that didn't quite work as well.

I'm on NodeJS. How can I leverage Async or some other library to solve my problem?

I want to wait for 15 seconds then loop to the second object. Not sure how this is achieved. (Async.serial?)

  • R
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use promise pattern with Q. Your function should return a promise and things will be easier:

Q.all(users.map(user => smsFree.sendSMSFree(userData, productUrl)))
       .then(() => {
           // Do stuff once every SMS has been successfully sent!
       }); 

Or standard Promise:

Promise.all(users.map(user => smsFree.sendSMSFree(userData, productUrl)))
       .then(() => {
           // Do stuff once every SMS has been successfully sent!
       }); 

If your function doesn't use promise pattern you can either wrap it to use the whole pattern or you'll be stuck in terms of implement asynchronous continuations...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...