【问题标题】:Using promises in async function在异步函数中使用 Promise
【发布时间】:2020-08-13 08:38:36
【问题描述】:

我正在尝试侦听 Stripe webhook 调用,然后执行一些操作,例如发送电子邮件。我的网站在 Netlify 上,我已经修改了在 tutorial 中找到的一些代码:

这可以在本地工作,但当我将它作为 Netlify 函数(基本上是 lambda)运行时却不行。基本上,来自“client.getSpace..”的部分似乎根本没有运行。我怀疑这与在异步函数中使用这些 .then 承诺有关,但我不确定。

require('dotenv').config();
     const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    
     const contentful = require('contentful-management');
     const client = contentful.createClient({
      accessToken: 
    process.env.CONTENTFUL_CONTENT_MANAGEMENT_ACCESS_TOKEN
    });
    
    var postmark = require("postmark");
    var serverToken = process.env.POSTMARK_SERVER_TOKEN;
    var postmark_client = new postmark.ServerClient(serverToken);
    
    exports.handler = async ({ body, headers }) => {
    try {
      const stripeEvent = stripe.webhooks.constructEvent(
        body,
        headers['stripe-signature'],
        process.env.STRIPE_WEBHOOK_SECRET
      );
    
      if (stripeEvent.type === 'checkout.session.completed') {
      	console.log('confirm checkout session completed');
        const eventObject = stripeEvent.data.object;
        const entryId = eventObject.client_reference_id;
        let email = "";
        let secret = "";
    
      client.getSpace(process.env.WEBSITE_CONTENTFUL_SPACE_ID)
      	.then(space => space.getEnvironment('master'))
          .then(environment => environment.getEntry(entryId))
          .then(entry => {
          	entry.fields.paymentStatus['en-GB'] = 'Paid';
          	email = entry.fields.email['en-GB'];
          	return entry.update();
          })
          .then(entry => entry.publish())
      	.then(entry => postmark_client.sendEmailWithTemplate({
              "From": "x@test.com",
              "To": email,
              "TemplateId": 12345678,
              "TemplateModel": {
                  "abc": "xyz"
               }
            }))
          .catch(console.error)
    
      }
    
      return {
        statusCode: 200,
        body: JSON.stringify({ received: true }),
      };
      } catch (err) {
      console.log(`Stripe webhook failed with ${err}`);
    
      return {
        statusCode: 400,
        body: `Webhook Error: ${err.message}`,
      };
    }
    };

【问题讨论】:

  • 您是否尝试过使用await 而不是then 语法?
  • client.getSpace() 链异步运行, 你返回一个状态码。也许当处理程序返回时,netlify 会杀死环境?
  • @Bergi - 不,我没有。我为这个(内容 API)代码提供的所有示例都使用 then 语法。看起来怎么样?
  • @Bergi - 至于你的第二个问题,我想知道我自己,但 if 语句中的代码正在运行......我用 console.log('confirm checkout session completed');

标签: javascript asynchronous netlify netlify-function


【解决方案1】:

对于您和遇到此问题的任何其他人来说,这有什么价值。我在 Vercel 上使用 NextJS 时遇到了类似的问题。我使用 async/await 重写了 .then 语法,到目前为止,问题似乎已经解决。我不是专家,但我认为在这种情况下,您应该先替换

  client.getSpace(process.env.WEBSITE_CONTENTFUL_SPACE_ID)
    .then(space => space.getEnvironment('master'))

类似的东西

       const send = await client.getSpace(process.env.WEBSITE_CONTENTFUL_SPACE_ID)
       const getEnvironment = await space.getEnvironment('master')

以此类推。我不确定您将如何重写其他所有内容,或者这是否会有所帮助,但它让我回到了正轨。

【讨论】:

    猜你喜欢
    • 2020-01-22
    • 2021-02-15
    • 2021-06-28
    • 2018-01-02
    • 2019-11-06
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多