【发布时间】: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