所以我试图在异步函数中操作这个变量,并且我知道该变量是在我将在下面显示的 data.map 函数完成之前返回的,但我很好奇为什么?我在前面有 wait 关键字,试图暂停代码,直到 .map 函数完成,然后它应该从 .map 函数返回计数,但事实并非如此,我很好奇我做错了什么以及是否有有更好的方法吗?谢谢你!代码:const alertFetch = async () => { //set a count at the beginning of the endpoint var counter = 0; await data["option_activity"].map(async (item) => { var reply = await GET_ASYNC("alert_" + item.id); if (reply) { //If they are a repeat return nothing // console.log('No New Alert Detected') } else { //If they arent a repeat store the alert // console.log("New alert detected") const saveResult = await SET_ASYNC( "alert_" + item.id, JSON.stringify(item), "EX", 604800 ); //Push it to array list in redis await client.get("alert_" + item.id, function (err, reply) { client.rpush("alerts", reply); }); //Increment counter to represent how many new alers counter = counter + 1; } }); console.log(counter); return counter; };
1 回答
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
就你而言,data['option_activity'].map这不是一个承诺。
看这个例子:
let sample_arr= Array.from({ length: 10}, () => Math.floor(Math.random() * (10 - 1) + 1));
let f= async(arr)=>{
await Promise.all(arr.map(async item=>console.log(
await new Promise(r=>setTimeout(()=>r(item),2000)))
));
console.log('after all promises concurrent fulfilled.');
}
f(sample_arr);
添加回答
举报
0/150
提交
取消