用-awaitasync-正确链接-Javascript-中的多个函数

7次阅读

共计 3811 个字符,预计需要花费 10 分钟才能阅读完成。

作者:Dunk

翻译:疯狂的技术宅

原文:https://nikodunk.com/how-to-c…

未经允许严禁转载

在我完成 electrade 的工作之余,还帮助一个朋友的团队完成了他们的项目。最近,我们希望为这个项目构建一个 Craiglist 风格的匿名电子邮件中继,其中包含“serverless”Google Firebase Function(与 AWS Lambda,Azure Function 等相同)。到目前为止,我发现用 .then() 回调处理异步操作更容易思考,但是我想在这里用 async/await,因为它读起来更清晰。我发现大多数关于链接多个函数的文章都没有用,因为他们倾向于发布从 MSDN 复制粘贴的不完整的演示代码。在 async/await 上有一些难以调试的陷阱,因为我遇到了所有这些陷阱,所以我将在这里发布自己的完整代码并解释我的学习过程。

这是连接多个函数的工作代码,等待解决所有问题,然后 then 发送结果。主要错误是:

  1. 每个 async function myFunction(){ <your code here>} 声明 自动 将整个异步函数的代码(即 <your code here>)包装在 new Promise 中,然后转换为 return x 并在代码中加入 resolve(x)但是你还需要在它之外等待 (即 let y = await myFunction() 或它实际上不会等待。这个调试是非常烦人的。
  2. 在云函数中,你 必须 发送带有 res.send() 的响应,否则函数会认为它失败并重新运行它。

下面的代码要做这些事情:

  • 我们有 2 个正常的同步函数 getFieldsFromRequest()extractCourseIdFromEmailAddress() —— 这里没问题。
  • 然后我们需要 async 函数 getEmailOfCourseWithCourseId() 从 Firestore 获取课程的电子邮件地址。我们不知道从 Firestore 获取内容需要多长时间,因此它是 async 的,我们需要运行接下来的两个函数并返回(或以 promise 解析)courseEmail
  • 接下来的两个函数 saveToCloudFirestore()sendEmailInSendgrid(),不能在 getEmailOfCourseWithCourseId() 之前运行并返回 courseEmail,否则它们将认为 courseEmail 未定义,这样的话一切都变得糟透了。通过 awaiting 上面的函数 getEmailOfCourseWithCourseId() 并传递 courseEmail,这些函数(以及 if 运算符)将等到这种情况发生(也就是说已经解决),然后运再行。
  • 最后,在运行 saveToCloudFirestore()sendEmailInSendgrid() 并返回它们的值之前,不能发送 res.send(),否则我们的整个云函数将在工作完成之前中断。为此,我们将 saveToCloudFireStore()sendEmailInSendgrid() 响应(它们返回的内容)保存到变量 中,其唯一目的是标记上述函数何时完成。这在某种意义上取代了 .then():它等待这两个变量(savedToCloudsentEmail)“到达”(他们的 Promise 已经解决),然后运行 res.send)()
  • 为了便于阅读,我已经 删除了你应该在实践中进行的 try/catch 包装。你永远不应该捕获错误,但删除它们会使 async/await 概念更容易理解。
// this is the cloud function you can call over HTTP. It is basically for email relay:
// it gets an email from sendgrid, parses the fields, looks up the real email with the courseId,
// saves to FireStore and sends and email with sendgrid.
// Finally, it sends a res.send() to end the cloud function

// {* import a bunch of shit *}

// main function
exports.emailFunction = functions.https.onRequest(async (req, res) => {let fields = getFieldsFromRequest(req); // sync
  let courseId = extractCourseIdFromEmailAddress(fields); // sync
  let courseEmail = await getEmailOfCourseWithCourseId(courseId); // async
  let savedToCloud = await saveToCloudFirestore(fields, courseEmail, courseId); // async
  let sentEmail = await sendEmailWithSendgrid(fields, courseEmail);  // async
  res.status(200).send(savedToCloud, sentEmail); // Once sentEmail and saveToCloud have been returned (aka promises have been resolved, aka their functions have been run), res.send() will run so Firebase/SendGrid know that func worked.});

// Helper functions below
function getFieldsFromRequest(req) { // sync
    let fields = readTheFieldsFromReqWithBusboy(req)
    return fields;
}

function extractCourseIdFromEmailAddress(fields) { // sync
    let courseId = fields.to.substring(0, fields.to.indexOf('@'));
    return courseId;
}

async function getEmailOfCourseWithCourseId(courseId) { // async important
    let courseData = await database.get(courseId)
    let courseEmail = courseData.email;
    return courseEmail; // due to function being labeled async above, this is the equivalent of wrapping the whole function in 'return new Promise(resolve) => {}' and then returning a 'resolve(result)'
}

async function sendEmailWithSendgrid(fields, courseEmail) { // async important
    let msg = {to: courseEmail, from: fields.from, text: fields.text}
    let sentEmail = await sendgrid.send(msg)
    return sentEmail; // due to function being labeled async above, this is the equivalent of wrapping the whole function in 'return new Promise(resolve) => {}' and then returning a 'resolve(result)'
}

async function saveToCloudFirestore(fields, courseEmail, courseId) { // async important
    let savedToCloud = await database.add(fields, courseEmail, courseId)
    return savedToCloud;
}

最后 try {}catch {} 包装最后 3 个异步函数和主函数来捕获错误。此外,数据库代码不能原封不动的复制 —— 它仅用于说明目的!


本文首发微信公众号:前端先锋

欢迎扫描二维码关注公众号,每天都给你推送新鲜的前端技术文章

欢迎继续阅读本专栏其它高赞文章:

  • 深入理解 Shadow DOM v1
  • 一步步教你用 WebVR 实现虚拟现实游戏
  • 13 个帮你提高开发效率的现代 CSS 框架
  • 快速上手 BootstrapVue
  • JavaScript 引擎是如何工作的?从调用栈到 Promise 你需要知道的一切
  • WebSocket 实战:在 Node 和 React 之间进行实时通信
  • 关于 Git 的 20 个面试题
  • 深入解析 Node.js 的 console.log
  • Node.js 究竟是什么?
  • 30 分钟用 Node.js 构建一个 API 服务器
  • Javascript 的对象拷贝
  • 程序员 30 岁前月薪达不到 30K,该何去何从
  • 14 个最好的 JavaScript 数据可视化库
  • 8 个给前端的顶级 VS Code 扩展插件
  • Node.js 多线程完全指南
  • 把 HTML 转成 PDF 的 4 个方案及实现

  • 更多文章 …
正文完
 0