Render the results of two separate async.each methods.

huangapple go评论84阅读模式
英文:

Render the results of two separate async.each methods

问题

我是你的中文翻译,以下是代码的翻译部分:

我是新手使用Node.js和async。我有困难理解如何包装两个单独的async.each方法,以便有一个res.render...我试图在前端显示有效的账户ID列表和有效的用户ID。

两个单独的async.each方法如下:

async.each(account_ids, function(accountId, callback) {
    console.log('处理账户ID ' + accountId);

    调用外部API(accountId, callback, function(err, response){
      if(err){
        console.log("账户错误");
      }
      console.log("账户响应是: ", response);
    });

  }, function(err) {
    if( err ) {
      console.log('某个账户处理失败');
    } else {
      console.log('所有账户已成功处理');
    }
  });

async.each(email_ids, function(emailId, callback) {
    console.log('处理电子邮件ID ' + emailId);
    request({
      url: emailIdlookupUrl,
      method: 'POST',
      json: {
        email_address: emailId
      }
    }, function (err, response, body) {
      if (err) {
        logger.error(err);
        req.flash('error', err.message);
        return res.redirect('?');
      }
      if (response.statusCode !== 200) {
        const msg = '无法验证用户';
        req.flash('error', msg);
        return res.redirect('?');
      }
      console.log("用户ID是: ", body.user.id);
      callback();
    });

  }, function(err) {
    if( err ) {
      console.log('某封电子邮件处理失败');
    } else {
      console.log('所有用户电子邮件已成功处理');
    }
  });

希望对你有所帮助。请原谅我可能存在的冗余回调或错误日志记录。我仍在学习Node.js。感谢!

英文:

I am new to nodejs and async. Having trouble understanding how can I wrap the two separate async.each methods to have one res.render...I am trying to display a list of valid account ids, and valid user ids on the front end.
The two separate async.each methods are:

async.each(account_ids, function(accountId, callback) {
        console.log('Processing accountId ' + accountId);

        callingExternalApi(accountId, callback, function(err, response){
          if(err){
            console.log("error account");
          }
          console.log("account response is: ", response);
        });

      }, function(err) {
        if( err ) {
          console.log('An account failed to process');
        } else {
          console.log('All accounts have been processed successfully');
        }
      });

and

async.each(email_ids, function(emailId, callback) {
        console.log('Processing email id ' + emailId);
        request({
          url: emailIdlookupUrl,
          method: 'POST',
          json: {
            email_address: emailId
          }
        }, function (err, response, body) {
          if (err) {
            logger.error(err);
            req.flash('error', err.message);
            return res.redirect('?');
          }
          if (response.statusCode !== 200) {
            const msg = 'Unable to verify user';
            req.flash('error', msg);
            return res.redirect('?');
          }
          console.log("user id is: ", body.user.id);
          callback();
        });

      }, function(err) {
        if( err ) {
          console.log('An email failed to process');
        } else {
          console.log('All user emails have been processed successfully');
        }
      });

Any help is highly appreciated. Please excuse me for any redundant callbacks or error logging. Still learning nodejs.

Thanks!!

答案1

得分: 1

以下是您要翻译的内容:

主要问题不在于您调用了这两个async.each调用。问题在于它们将并行运行,最先调用req.*函数或回调函数的速度将返回连接的响应。

如果省略了它们的回调参数,这两个函数都会返回promises。

我建议您阅读有关async库和JS async/await的一般信息:

请注意,async还接受原生的异步函数,这使得代码更加清晰和易于理解。

以下是我认为您想要的代码,包括将结果编译成列表:

var request = require("request-promise");

async function checkAccounts(account_ids) {
  const valid_accounts = [];
  await async.each(account_ids, async function(accountId) {
    console.log("Processing accountId " + accountId);
    const extAPIresult = await callingExternalApi(accountId);
    console.log("account response is: ", extAPIresult);
  });
  valid_accounts.push(extAPIresult);
  console.log("All accounts have been processed successfully");
  return valid_accounts;
}

async function checkEmails(email_ids) {
  const valid_emails = [];
  await async.each(email_ids, async function(emailId) {
    console.log("Processing email id " + emailId);
    const reqresult = await request({
      url: emailIdlookupUrl,
      method: "POST",
      json: {
        email_address: emailId
      }
    });
    if (reqresult.statusCode !== 200) {
      throw new Error("Unable to verify user");
    }
    valid_emails.push(reqresult.body.user.id);
    console.log("user id is: ", reqresult.body.user.id);
  });
  console.log("All emails have been processed successfully");
  return valid_emails;
}

async function doChecks() {
  const accounts = checkAccounts(account_ids);
  const emails = checkEmails(email_ids);
  const responses = await Promises.all([accounts, emails]);
  console.log("All checks have been processed successfully");
  return responses;
}

function get(req, res) {
  doChecks()
    .then(responses => {
      res.send("All checks have been processed successfully");
      res.send(String(responses));
    })
    .catch(err => {
      req.flash("error", err.message);
      res.redirect("?");
    });
}

希望这有助于您的项目!

英文:

The main issue is not that you are invoking both of these async.each calls. The problem is that they will run in parallel, and the fastest one to invoke req.* functions or callback function will return a response to the connection.

Both of these functions return promises if their callback parameters are omitted.

I recommend reading up on both the async library and JS async/await in general:

Note that async also accepts native async functions, which many finder cleaner and easier to understand.

Here is what I think you want from the code above, including compiling the results into lists:

var request = require("request-promise");
async function checkAccounts(account_ids) {
const valid_accounts = [];
await async.each(account_ids, async function(accountId) {
console.log("Processing accountId " + accountId);
const extAPIresult = await callingExternalApi(accountId);
console.log("account response is: ", extAPIresult);
});
valid_accounts.push(extAPIresult);
console.log("All accounts have been processed successfully");
return valid_accounts;
}
async function checkEmails(email_ids) {
const valid_emails = [];
await async.each(email_ids, async function(emailId) {
console.log("Processing email id " + emailId);
const reqresult = await request({
url: emailIdlookupUrl,
method: "POST",
json: {
email_address: emailId
}
});
if (reqresult.statusCode !== 200) {
throw new Error("Unable to verify user");
}
valid_emails.push(reqresult.body.user.id);
console.log("user id is: ", reqresult.body.user.id);
});
console.log("All emails have been processed successfully");
return valid_emails;
}
async function doChecks() {
const accounts = checkAccounts(account_ids);
const emails = checkEmails(email_ids);
const responses = await Promises.all([accounts, emails]);
console.log("All checks have been processed successfully");
return responses;
}
function get(req, res) {
doChecks()
.then(responses => {
res.send("All checks have been processed successfully");
res.send(String(responses));
})
.catch(err => {
req.flash("error", err.message);
res.redirect("?");
});
}

huangapple
  • 本文由 发表于 2020年1月7日 00:25:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定