亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Await 關鍵字在承諾履行之前沒有正確停止?

Await 關鍵字在承諾履行之前沒有正確停止?

牛魔王的故事 2024-01-18 15:43:59
所以我試圖在異步函數中操作這個變量,并且我知道該變量是在我將在下面顯示的 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);


查看完整回答
反對 回復 2024-01-18
  • 1 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號