[英]How to make an API call using async function?
我是node.js的新手,我正在尝试将公司的后端从python迁移到node.js
现在,我使用express创建了一个node.js服务器。 路线正常。 我的公司使用WooCommerce,他们有一个node.js库。 我的代码是这样的:
const WooCommerceAPI = require("woocommerce-api");
class WooCommerceController {
async getOrders(req, res) {
const orders = await WooCommerce.get("orders", function(err, data, res) {
return res;
});
return res.json(orders);
}
}
module.exports = new WooCommerceController();
我知道
WooCommerce.get("orders", function(err, data, res) {
console.log(res);
});
之所以有效,是因为如果执行此函数,它将返回我公司的订单列表,但是,如果我尝试将其放入此async
await
,它将返回WooCommerce API的状态,而不是API的响应。
我究竟做错了什么?
WooCommerce.get
使用回调,而await
仅使用返回Promise
函数。 因此,您需要自己创建一个util.promisify
,并在回调中手动解决它,或者您可以使用util.promisify
将回调函数(带有(err, value)
回调参数)自动转换为Promise样式的函数。
const wooGetPromise = util.promisify(WooCommerce.get);
...
const orders = await wooGetPromise("orders");
...
编辑:感谢RichS查找API:我的wooGetPromise
已经作为WooCommerce.getAsync
存在。
使用该功能的选项有:
WooCommerce.getAsync('orders').then(function(result) {
return JSON.parse(result.toJSON().body);
});
var result = await WooCommerce.getAsync('orders');
var json = JSON.parse(result.toJSON().body);
hello mate await通常会解析诺言,因此在await关键字之后调用的函数应该是返回诺言的函数或默认返回诺言的asyn函数。
异步功能
WooCommerce.get("orders", async function(err, data, res) {
return res;
});
或返回承诺的函数
WooCommerce.get("orders", function(err, data, res) {
return new Promise(function(resolve, reject){
err ? reject(err) : resolve(res);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.