[英]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.