简体   繁体   中英

How to make an API call using async function?

I'm new to node.js and I'm trying to migrate the backend of my company from python to node.js

Right now I created a node.js server using express. The route works fine. My company uses WooCommerce, and they have a node.js library. My code is this one:

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();

I know that

WooCommerce.get("orders", function(err, data, res) {
      console.log(res);
    });

works, because if I execute this function it returns the list of orders of my company, however if I try to put it inside this async await , it returns the status of the WooCommerce API, not the response of the API.

What am I doing wrong?

WooCommerce.get works with a callback, while await only works with functions that return a Promise . So either you need to create a promise yourself, and manually resolve it in the callback, or you can use util.promisify to automatically convert the callback-function (with an (err, value) callback parameters) to a Promise-style function.

const wooGetPromise = util.promisify(WooCommerce.get);
...
const orders = await wooGetPromise("orders");
...

EDIT: Thanks to RichS for looking up the API: my wooGetPromise already exists as WooCommerce.getAsync .

The options for using that function are:

  1. With then :
    WooCommerce.getAsync('orders').then(function(result) {
       return JSON.parse(result.toJSON().body);
    });
  1. With await (only in async function):
    var result = await WooCommerce.getAsync('orders');
    var json = JSON.parse(result.toJSON().body);

hello mate await usually resolves a promise so the function that is being called after the await key word should be a function that returns a promise or an asyn function which by default returns a promise.

Async function

WooCommerce.get("orders", async function(err, data, res) {
      return res;
}); 

Or a function that returns a promise

WooCommerce.get("orders", function(err, data, res) {
  return new Promise(function(resolve, reject){
   err ? reject(err) : resolve(res);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM