首页 > 解决方案 > MongoDB Stitch Functions 是否支持 async/await 定义?

问题描述

MongoDB (Atlas) Stitch 上的异步函数定义在 GUI 编辑器上显示警告。包括触发器参考中提供的示例代码。

此处找到的代码可以直接复制到 Stitch Function 编辑器并由于 async 关键字而产生警告。

来自文档的示例代码。

exports = async function (changeEvent) {
  // Destructure out fields from the change stream event object
  const { updateDescription, fullDocument } = changeEvent;

  // Check if the shippingLocation field was updated
  const updatedFields = Object.keys(updateDescription.updatedFields);
  const isNewLocation = updatedFields.some(field =>
    field.match(/shippingLocation/)
  );

  // If the location changed, text the customer the updated location.
  if (isNewLocation) {
    const { customerId, shippingLocation } = fullDocument;
    const twilio = context.services.get("myTwilioService");
    const mongodb = context.services.get("mongodb-atlas");
    const customers = mongodb.db("store").collection("customers");

    const { location } = shippingLocation.pop();
    const customer = await customers.findOne({ _id: customer_id })
    twilio.send({
      to: customer.phoneNumber,
      from: context.values.get("ourPhoneNumber"),
      body: `Your order has moved! The new location is ${location}.`
    });
  }
};

我想知道 Stitch 是否支持 async/await 范式,以及我是否应该关注显示的警告。

标签: javascriptmongodbasync-awaitmongodb-stitch

解决方案


经过一番测试,我发现此时async/await关键字会导致 linter 抛出错误和警告。这意味着对于异步回调,最好单独定义它们,因为它会改进 linting。IE。[].map(async () => {})将提示可以解决的错误。

运行时执行返回标准异步操作的预期结果。


推荐阅读