我们在调用中为某些fs函数使用了async / await语法,并希望引入Woocommerce API调用并使用async / await,但是我在语法上苦苦挣扎。
const WooCommerceAPI = require('woocommerce-api');
exports.handler = async (event, context, callback) =>{
const orderFileName ="1141";
let wooOrderDetails;
var WooCommerce = new WooCommerceAPI({
url: 'http: //example.com',
consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
wpAPI: true,
version: 'wc/v1'
});
WooCommerce.getAsync('orders/' + orderFileName).then(function(result){
return JSON.parse(result.toJSON().body);
wooOrderDetails = JSON.parse;
console.log(wooOrderDetails);
let wooOrderID = wooOrderDetails.id;
let wooOrderNumber = wooOrderDetails.number;
let Email = wooOrderDetails.billing.email;
});
// Update order as Completed
const status ={
status: 'completed'
};
// Update WooCommerce Order Notes via API
WooCommerce.post('orders/' + orderFileName, status, function (err, states, res){
if (err) throw err;
console.log('Update WooCommerce order with status');
const data ={ note: 'Status Updated';
});
WooCommerce.post('orders/' + orderFileName + '/notes', data, function (err, data, res){
if (err) throw err;
else console.log('Woo Order Notes Update:');
});
});
});
};
NPM module有一些异步示例,但我无法使它们正常工作。我主要是认为函数的返回过程存在问题
答案 0 :(得分:0)
基本上,您将xyzAsync(a,b).then(result => {code})
转换为result = await xyzAsync(a,b); code;
。因此,您的第一个getAsync
(其中包含一些小错误,顺便说一句)变为:
const result = await WooCommerce.getAsync('orders/' + orderFileName)
const wooOrderDetails = JSON.parse(result.toJSON().body);
console.log(wooOrderDetails);
let wooOrderID = wooOrderDetails.id;
let wooOrderNumber = wooOrderDetails.number;
let Email = wooOrderDetails.billing.email;
答案 1 :(得分:0)
以下是异步等待样式的错误修复和工作代码:
exports.handler = async(event, context, callback) => {
const orderFileName = "1141";
let wooOrderDetails;
const WooCommerce = new WooCommerceAPI({
url: 'http: //example.com',
consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
wpAPI: true,
version: 'wc/v1'
});
const result = await WooCommerce.getAsync('orders/' + orderFileName);
wooOrderDetails = JSON.parse(result.toJSON().body);
console.log(wooOrderDetails);
let {id: wooOrderID, number:wooOrderNumber, billing} = wooOrderDetails;
let {email} = billing;
// Update order as Completed
const status = {
status: 'completed'
};
// Update WooCommerce Order Notes via API
try {
const statusResults = await WooCommerce.post('orders/' + orderFileName, status);
console.log('Update WooCommerce order with status');
const data = {note: 'Status Updated'};
const notesResults = await WooCommerce.post('orders/' + orderFileName + '/notes', data);
console.log('Woo Order Notes Update:');
} catch (e) {
// throw error or take actions you want
}
};