I am looking to change a couple of Woocommerce API calls so each function finishes before the next functions proceeds. However, I am unsure how to do this without breaking the specific Node Woocommerce API code.
https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#create-an-order-note
How can I change those two Woocommerce POST functions to Async/Await so it works with AWS Lambda?
(I have included an existing await function currently used in AWS Lambda as a reference)
const WooCommerceAPI = require('woocommerce-api');
const path = require('path');
const util = require('util');
exports.handler = async (event, context, callback) => {
// AWAIT EXAMPLE in LAMBDA -- Outputs the /tmp/ contents to the console.
const readdirs = util.promisify(fs.readdir);
await readdirs('/tmp/').then((files) => {
console.log('Check tmp contents')', files);
}).catch((err) => {
console.log(err);
});
// Update Woocommerce order
const WooCommerce = new WooCommerceAPI({
url: process.env.WOOAPI_URL, // Your store URL
consumerKey: process.env.WOOAPI_KEY, // Your consumer key
consumerSecret: process.env.WOOAPI_SECRET, // Your consumer secret
wpAPI: true, // Enable the WP REST API integration
version: 'wc/v3' // WooCommerce WP REST API version
});
//Set order as complete
const status = { status: 'completed' };
WooCommerce.post('orders/' + orderId, status, function (err, states, res) {
if (err) throw err;
else console.log('Update WooCommerce order with status');
});
const data = { note: 'Please check www.example.com for full instructions' };
WooCommerce.post('orders/' + orderId + '/notes', data, function (err, data, res) {
if (err) throw err;
else console.log('Manual WooCommerce Order Note');
});
};
Advertisement
Answer
There’s a method called postAsync
for async calls in WooCommerce, you can try something like:
const status = {
status: 'completed'
};
const ordersResult = await WooCommerce.postAsync(`orders/${orderId}`, status).then((data) => {
console.log('Update WooCommerce order with status');
}, (err) => {
console.log(err);
});
const noteData = {
note: 'Please check www.example.com for full instructions'
};
const notesResult = await WooCommerce.postAsync(`orders/${orderId}/notes`, noteData).then((data) => {
console.log('Manual WooCommerce Order Note');
}, (err) => {
console.log(err);
});
Every method can be used in a promified way just adding Async to the method name.
You can take a look to the docs here: https://github.com/woocommerce/wc-api-node#promified-methods
If it doesn’t work, you can always use it stacking calls like this:
const status = {
status: 'completed'
};
WooCommerce.post('orders/' + orderId, status, function(err, states, res) {
if (err) throw err;
console.log('Update WooCommerce order with status');
const data = {
note: 'Please check www.example.com for full instructions'
};
WooCommerce.post('orders/' + orderId + '/notes', data, function(err, data, res) {
if (err) throw err;
console.log('Manual WooCommerce Order Note');
});
});