调用两个异步函数

Calling two async functions

我是 async 和 await 的新手,我正在考虑在 express api 端点中调用两个 Stripe API。这可能吗?

server.post('/ephemeral_keys', async (req, res) => {
    let customerId = req.body["customerId"];

    //TODO IF customerId is null create new one 
    //It got stuck here.
    customerId = await stripe.customers.create({
        description: 'My First Test Customer (created for API docs)',
    });

    let key = await stripe.ephemeralKeys.create({
        customer: customerId
    }, {
        apiVersion: api_version
    }, );
    res.json(key);
});

错误:弃用警告:未处理的承诺拒绝已弃用。将来,未处理的承诺拒绝将以非零退出代码终止 Node.js 进程。

您可以在此处使用 if 语句:

...
//TODO IF customerId is null create new one 
if(!customerId) {
  customerId = await stripe.customers.create({
    description: 'My First Test Customer (created for API docs)',
  });
}
...

是的,您可以按顺序有多条 await 行,处理将在每个响应返回后按顺序 运行。

请注意,在您的示例中,当创建客户时,您需要提取 id,而不是在第二个请求中使用完整的客户对象:

server.post('/ephemeral_keys',async (req,res)=>{
  let customerId = req.body["customerId"];
 
  if (!customerId) {
    const newCustomer = await stripe.customers.create({
      description: 'My First Test Customer (created for API docs)',
    });
    customerId = newCustomer.id; // make sure to only use the id from the object
  }
  

  let key = await stripe.ephemeralKeys.create(
    { customer: customerId },
    { apiVersion: api_version }, 
  );
  res.json(key);
});