Reputation:
I'm new to async and await and I'm thinking about calling two Stripe APIs in an express api endpoint. Is that possible?
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);
});
error :DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Upvotes: 0
Views: 33
Reputation: 12240
You can use an if
statement here:
...
//TODO IF customerId is null create new one
if(!customerId) {
customerId = await stripe.customers.create({
description: 'My First Test Customer (created for API docs)',
});
}
...
Upvotes: 0
Reputation: 7449
Yes you can have multiple await
lines in sequence, and the processing will run sequentially after each response comes back.
Note in your example that when the customer is created, you'll need to pull off the id
, instead of using the full customer object in the second request:
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);
});
Upvotes: 0