javascript 如何使forEach循环同步

eulz3vhy  于 2023-05-12  发布在  Java
关注(0)|答案(5)|浏览(473)

我这里有个异步问题。当res.json({ errors });返回时,forEach仍在运行,因此不会拾取所有错误。我该怎么办?

router.post('/new/user', async function (req, res, next) {
    const validateEmail = async (email) => {
      var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return re.test(email);
    };
    
    const reqBody = { email, password };
    
    let errors = {};

    Object.keys(reqBody).forEach(async (field) => {
      if (field === 'email' && validateEmail(await reqBody[field])) {
        errors = { ...errors, [field]: 'Not a valid Email' };
      }
      console.log(3);
    
      if (field === 'password' && password !== '' && password < 4) {
        errors = { ...errors, [field]: 'Password too short' };
      }
    });
    
    if (Object.keys(errors).length > 0) {
      res.json({ errors });
    }
}
vltsax25

vltsax251#

使用for...of来循环数组元素,您可以使用await

for(const field of Object.keys(reqBody)){
   //Code using await
}
wxclj1h5

wxclj1h52#

使用map而不是forEach来获取promise Object.keys(reqBody).map(async (field) => {...},然后使用Promise. allSettled来等待所有promise解决或被拒绝,您可以捕获该错误以记录

router.post('/new/user', async function (req, res, next) {
    const validateEmail = async (email) => {
      var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return re.test(email);
    };
    
    const reqBody = { email, password };
    
    try{
      const promises =  Object.keys(reqBody).map(async (field) => {
      if (field === 'email' && validateEmail(await reqBody[field])) {
        Promise.reject({[field]: 'Not a valid Email'})
      }
      console.log(3);
    
      if (field === 'password' && password !== '' && password < 4) {
        Promise.reject({[field]: 'Password too short'})
      }
     });
     // List of resolved and rejected promises
     const results = await Promise. allSettled(promises)
     const errors = results.filter(result => result.status === "rejected")
     if (Object.keys(results).length > 0) {
        res.json({ errors });
     }
    }catch(error){
      res.json({ error });
    }
}
xlpyo6sf

xlpyo6sf3#

我不喜欢异步循环函数中的等待语法。但是如果我保留现有的map结构,我可能会在它之外添加一个数组来保存空白promise。每次循环时将promise推入该数组,然后在await和推入错误后解决它。然后将awaitPromise.all放在对象键循环和设置响应之间的数组上。

vql8enpb

vql8enpb4#

在处理异步内容时,在Object.keys(reqBody)上使用普通的for循环要容易得多。

let keys =  Object.keys(reqBody)
for(let i in keys){
   ...
}
zwghvu4y

zwghvu4y5#

你可以用函数的方法来使每一个同步。

async function deleteCred(data) {
  data.forEach(function (element) {
    if(element.credentials[0]){
    delete element.credentials[0].consumerKey;
    delete element.credentials[0].consumerSecret;
    }
  });
  return data;
}

deleteCred(data).then(function (data) {
//code here
console.log(data);
 });

相关问题