var request = require('request'); //exports.httprequest = (requestData) =>{ function httprequest(requestData){ return new Promise((resolve, reject)=>{ var url = "http://xxx/_search" var option ={ url: url, method: "POST", json: true, headers: { "content-type": "application/json", }, body: requestData } request(option, function(error, response, body) { if (!error && response.statusCode == 200) { resolve(body) } }); }); }; var data = { xxx } httprequest(data).then(function(req){ console.log(req) })
当多个请求需要全部完成后返回结果可以使用 Promise.all()
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
使用request-promise模块代码结构更清晰
https://www.npmjs.com/package/request-promise
彻底了解nodejs中的回调
https://blog.csdn.net/rockage/article/details/79513450