【问题标题】:Not able to get callback to work无法让回调工作
【发布时间】:2018-04-10 23:06:30
【问题描述】:

我正在使用 ExpressJS、NodeJS 构建 API

问题是当我使用 Postman 调用我的 API 时,我没有得到任何返回结果。我不知道如何让 Postman 等待函数返回 allproduct 结果。我正在使用回调,但它不起作用,我在代码的服务部分尝试了许多简单的回调代码,但它们都不起作用。只有 Async Await 使 Postman API 停止并等待结果,但是我使用的是名为 Pipedrive 的第三方 API,它仅适用于回调。如果我能以某种方式使 Pipedrive API 与 Async/Await 一起工作,它可能会解决我的问题

路线:

var express = require('express')

var router = express.Router()

// Push the job to different controller functions
var PipedriveController = require('../../controllers/pipedrive.controller');

router.get('/products', PipedriveController.pipedriveAllProducts)

// Export the router

module.exports = router;

控制器

var PipedriveService = require('../services/pipedrive.service')

// Async Controller Function

exports.pipedriveAllProducts = async function(req, res, next){
    // let family = req.param.options;

    try {
        let all_products = await PipedriveService.pipedriveAllProducts()

        //  Return All product liist with Appropriate HTTP header response
        return res.status(200).json({status: 200, all_products});
    } catch(e){

        // Return an Error Response Message
        return res.status(400).json({status: 400, message: e.message});
    }


}

服务:

var Pipedrive = require('pipedrive');
var pipedrive = new Pipedrive.Client('SECRET', { strictMode: true });

// Saving the context of this module inside the _the variable
_this = this




exports.pipedriveAllProducts = async function operation(options){
    // Array of product object - after which will be converted to JSON
    const allproducts = [];

    function iterateprods (err, products) {
        if (err) throw err;
        for (var i = 0; i < products.length; i++) {
            // console.log(products[i].prices["0"].price);

            let product = {
                "id": products[i].code,
                "name": products[i].name,
                "price": products[i].prices["0"].price
            }

            allproducts.push(product)

        }
        console.log(JSON.stringify(allproducts));
        return allproducts
    }

    pipedrive.Products.getAll({},iterateprods)


}

【问题讨论】:

  • 您需要将getAll 变成Promise 才能使用async/await。查看stackoverflow.com/questions/22519784/…
  • @Khang 谢谢,但我认为我将不得不坚持回调,因为我太菜鸟不敢冒险将回调转换为承诺
  • exports.pipedriveAllProducts 不返回任何内容。

标签: node.js express pipedrive-api


【解决方案1】:

首先,不需要你把async放在operation函数之前,你需要将你的服务包装在一个promise中,你可以这样做:

var Pipedrive = require('pipedrive');
var pipedrive = new Pipedrive.Client('SECRET', { strictMode: true });

// Saving the context of this module inside the _the variable
_this = this

exports.pipedriveAllProducts = function operation(options){
// Array of product object - after which will be converted to JSON
const allproducts = [];

return new Promise((resolve, reject) => {
       pipedrive.Products.getAll({}, function(err, products){
                if (err) reject(err);
                for (var i = 0; i < products.length; i++) {
                // console.log(products[i].prices["0"].price);

                let product = {
                    "id": products[i].code,
                    "name": products[i].name,
                    "price": products[i].prices["0"].price
                    }

               allproducts.push(product)

               }
         console.log(JSON.stringify(allproducts));
         resolve(allproducts);
          });
      }

【讨论】:

  • @OMG 非常感谢!这行得通!实际上我尝试了几次这种方法,但我遇到了失败。我会分析你的答案,看看我做错了什么!
猜你喜欢
  • 2019-11-17
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
相关资源
最近更新 更多