具有async/await样式功能的async.queue [英] async.queue with async/await style functions
问题描述
我正在尝试创建一个函数,该函数从对象数组构建队列,然后通过调用多个函数来处理每个对象.
处理功能是异步功能,在需要排队之前,我已经使用async/await模式实现了.我认为这是必要的,因为每个人都依赖于前一个的输出,并且我不想有大量的嵌套承诺.
即以前我有:
await Promise.all(messages.map(async(message) => {
let activity = await activityController.getActivity(message.activityId);
let url = await SMSController.getUrl(message.Token);
let smsSendResult = await SMSController.sendSMS(messageString, activity.mobileNo);
// etc...
}
现在我想做的是:
let queue = async.queue((message, done) => {
let activity = await activityController.getActivity(message.activityId);
let smsSendResult = await SMSController.sendSMS(messageString, activity.mobileNo);
// etc...
}
messages.forEach((message) => {
queue.push(message);
})
我有一个问题,尽管这样会导致
SyntaxError: await is only valid in async function
而且我似乎不太了解如何克服这个问题.
我在async模块中找到了asyncify函数,该函数允许我执行以下操作:
var queue = async.queue(async.asyncify(async (message, done) => {
let url = await SMSController.getUrl(message.token);
// etc...
}
I'm trying to create a function that builds a queue from an array of objects and then processes each object by calling a number of functions.
The processing functions are asynchronous functions which, prior to needing to queue, I'd implemented using the async/await pattern. I think this is necessary as each relies on the output of the previous and I don't want to have a tonne of nested promise.then's
i.e. previously I had:
await Promise.all(messages.map(async(message) => {
let activity = await activityController.getActivity(message.activityId);
let url = await SMSController.getUrl(message.Token);
let smsSendResult = await SMSController.sendSMS(messageString, activity.mobileNo);
// etc...
}
Now what I want to be able to do is:
let queue = async.queue((message, done) => {
let activity = await activityController.getActivity(message.activityId);
let smsSendResult = await SMSController.sendSMS(messageString, activity.mobileNo);
// etc...
}
messages.forEach((message) => {
queue.push(message);
})
I have the problem though that this results in
SyntaxError: await is only valid in async function
And I can't seem to quite get my head around how to get past this.
I found the asyncify function in the async module which allows me to do this:
var queue = async.queue(async.asyncify(async (message, done) => {
let url = await SMSController.getUrl(message.token);
// etc...
}
这篇关于具有async/await样式功能的async.queue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!