javascript - 如何使用异步函数进行API调用?

标签 javascript node.js

我是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 存在。

使用该功能的选项是:

  1. 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);
    

    关于javascript - 如何使用异步函数进行API调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55681882/

    相关文章:

    node.js - 我正在使用 Node.js 编写云函数,并且我想检查具有两个值(或条件)的单个字段

    node.js - Socket.io 发出欢迎来到 socket.io 消息

    javascript - 哇 js 不能使用滚动

    javascript - 如何仅通过 JavaScript 更改 URL 参数?

    node.js - 如何使用Nodejs Express获取发送请求的客户端的公共(public)IP地址?

    javascript - 如何在 Express 4.0 中发送 Flash 消息?

    node.js - 在famo.us 上运行着名的开发人员时出错

    javascript - Firefox 扩展与 Greasemonkey 脚本?

    javascript - 未捕获的类型错误 : Cannot convert undefined or null to object React JS

    javascript - 尝试将 React/Ajax 调用与 Spring MVC 和 Thymeleaf 结合使用