问题描述
我正在尝试发送短信以获取功能.但是问题是:该功能大约需要10到15秒才能完成(因为我们使用PhantomJS做了很多工作).
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);
});
我什至尝试使用setTimeout,但效果也不尽人意.
I've even tried using setTimeout but that didn't quite work as well.
我正在使用NodeJS.如何利用Async或其他库解决问题?
I'm on NodeJS. How can I leverage Async or some other library to solve my problem?
我想等待15秒,然后循环到第二个对象.不确定如何实现. (是Async.serial吗?)
I want to wait for 15 seconds then loop to the second object. Not sure how this is achieved. (Async.serial?)
- R
推荐答案
您应使用 承诺模式 和Q 一起使用.您的函数应该返回一个 promise ,事情将会变得更加简单:
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!
});
或标准Promise
:
Promise.all(users.map(user => smsFree.sendSMSFree(userData, productUrl)))
.then(() => {
// Do stuff once every SMS has been successfully sent!
});
如果您的函数不使用 promise模式,则可以将其包装起来以使用整个模式,否则您将陷入实现异步延续的困境...
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...
这篇关于异步等待功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!