如何使用异步函数进行API调用?
我是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
的函数。因此,您需要自己创建一个promise,并在回调中手动解析它,或者您可以使用util.promisify
自动将回调函数(使用(err, value)
回调参数)转换为Promise样式函数。
const wooGetPromise = util.promisify(WooCommerce.get);
...
const orders = await wooGetPromise("orders");
...
编辑:感谢RichS查找API:我的wooGetPromise
已经存在为WooCommerce.getAsync
。
使用该功能的选项是:
- 使用then:
WooCommerce.getAsync('orders').then(function(result) {
return JSON.parse(result.toJSON().body);
});
- 使用await(仅在异步函数中):
var result = await WooCommerce.getAsync('orders');
var json = JSON.parse(result.toJSON().body);
如何使用异步函数进行API调用?
我是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
的函数。因此,您需要自己创建一个promise,并在回调中手动解析它,或者您可以使用util.promisify
自动将回调函数(使用(err, value)
回调参数)转换为Promise样式函数。
const wooGetPromise = util.promisify(WooCommerce.get);
...
const orders = await wooGetPromise("orders");
...
编辑:感谢RichS查找API:我的wooGetPromise
已经存在为WooCommerce.getAsync
。
使用该功能的选项是:
- 使用then:
WooCommerce.getAsync('orders').then(function(result) {
return JSON.parse(result.toJSON().body);
});
- 使用await(仅在异步函数中):
var result = await WooCommerce.getAsync('orders');
var json = JSON.parse(result.toJSON().body);