使用 Async / Await 对来自 3 个不同循环的错误进行计数,这些循环在每次迭代中调用异步函数



我是Async/Await和Promises的新手,但我对Callbacks并不陌生。

在节点.JS服务器上,我正在尝试计算来自 3 个不同异步函数的数千个异步调用的错误,然后我想记录发生的错误量。 我有以下函数结构:

var sender = require('./sender');
module.exports = {
mainFunc : function (dataObjct){
this.func1(dataObjct.arr1);
this.func2(dataObjct.arr2);
this.func3(dataObjct.arr3);
},
func1 : function (arr){
for(let i=0;i<arr.length;i++){
sender.method1(arr[i]);
//sleep for 100 seconds cause i don't want too many messages at the same time
new Promise(resolve => setTimeout(resolve, '100'));
}
},
func2 : function (arr){
for(let i=0;i<arr.length;i++){
sender.method2(arr[i]);
//sleep for 100 seconds cause i don't want too many messages at the same time
new Promise(resolve => setTimeout(resolve, '100'));
}
},
func3 : function (arr){
for(let i=0;i<arr.length;i++){
sender.method3(arr[i]);
//sleep for 100 seconds cause i don't want too many messages at the same time
new Promise(resolve => setTimeout(resolve, '100'));
}
}
}

现在,sender.method1sender.method2sender.method3不同文件中的所有席位,它们内部都有一个异步调用。例如,这里是sender.method1

method1 : function(options){
const from = options.from;
const to = options.to;
const text = options.text;
someAsyncFunction(function(err,data) {if(err) console.log(err);},from,to,text);
}

我想计算来自sender.method1sender.method2sender.method3发生的所有错误,并仅在所有循环的所有异步调用完成后记录该数量的错误。

澄清我知道我的代码还没有准备好做我想做的事,我的问题是如何修改代码以实现我的目标。即使这意味着以不同的方式重写所有内容。

同步你的sender.methodx

通过承诺

method1 : function(options){
const from = options.from;
const to = options.to;
const text = options.text;
//ensure someAsyncFunction is a promise
return someAsyncFunction(function(err,data) {if(err) console.log(err);},from,to,text);
}

或通过回调(The Good'ol Way(

method1 : function(options, cb){
...
return someAsyncFunction(function(err,data) {
if(err){return cb(err)}
return cb(null);
},from,to,text);
}

我假设你返回一个promise

延迟批量

func1 : function (arr, oStat){
return arr.reduce((acc, x)=>{
//wait at least 100ms before next sender.method call
return Promise.all([
sender.methodX(x),
new Promise(resolve => setTimeout(resolve, 100))//no need to be a string btw
])
}, Promise.resolve())
}

捕获发件人方法错误以跟踪计数

这里固执己见:方法X之间的共享变量,以便在方法X终止之前有一个想法:

mainFunc : function (dataObjct){
let stats = {data1:{}, data2:{}, data3:{}};
this.func1(dataObjct.arr1, stats.data1);
this.func2(dataObjct.arr2, stats.data2);
this.func3(dataObjct.arr3, stats.data3);
},
func1 : function (arr, oStat){
oStat.count = 0;
return arr.reduce((acc, x)=>{
//wait at least 100ms before next sender.method call
return Promise.all([
sender.methodX(x).catch(e=>{
oStat.count++;
}),
new Promise(resolve => setTimeout(resolve, 100))//no need to be a string btw
])
}, Promise.resolve())
},

同步您的主函数

您不想重现someAsyncFunction的不可同步状态,因此不要在 void 中触发异步内容

mainFunc : function (dataObjct){
let stats = {data1:{}, data2:{}, data3:{}};
return Promise.all([
this.func1(dataObjct.arr1, stats.data1),
this.func2(dataObjct.arr2, stats.data2),
this.func3(dataObjct.arr3, stats.data3)
])
},

最新更新