Promise(避免金字塔回调)
前后端分离开发,前端通过接口获取数据,但是有的页面不止一个接口,就会出现金字塔回调,可以通过 Promise 封装请求。
request-data.js:
function reqData(posturl, req, res, callback) {//请求用户数据 request({ url: con.url + posturl, method: "POST", json: true, headers: { } }, function (error, response, body) { if (!error && response.statusCode == 200) { callback(body.code, body.data, null); } else { callback(null, null, "error"); } }); } function reqPostData(posturl, bodyData, req, res, callback) {//请求用户数据 request({ url: con.url + posturl, method: "POST", json: true, headers: { }, body: bodyData }, function (error, response, body) { if (!error && response.statusCode == 200) { callback(body.code, body.data, null); } else { callback(null, null, "error"); } }); }
viewData.js:
//引入数据请求模块 var requestData = require('./request-data'); function getNoParam(postUrl,req, res,describe) { var describe = describe || '数据'; //创建Promise对象 var p = new Promise(function(resolve, reject){ //发送获取相应数据的请求 requestData.reqData(postUrl, req, res, function (code, data, err) { if (code == 0) { //成功返回数据 resolve({Data:data}); } else { //失败说明原因 reject(describe + "获取失败:" + data); } }); }); return p; } function getWithParam(postUrl, postData,req, res,describe){ var describe = describe || '数据'; //创建Promise对象 var p = new Promise(function(resolve, reject){ //发送获取相应数据的请求 requestData.reqPostData(postUrl, postData, req, res, function (code, data, err) { // console.log(code, data, err); if (code == 0) { //成功返回数据 resolve({Data:data}); } else { //失败说明原因 reject(describe + "获取失败:" + data); } }); }); return p; }
路由文件调用:
var viewData = require('../modules/viewData'); /*商品列表*/ router.get('/list', function (req, res) { Promise .all([viewData.getNoParam('/user/hot_list', req, res, '热门列表'), viewData.getWithParam('/user/recommend_list', {id: req.query.id}, req, res, '推荐列表')]) .then( function (results) { res.render('index/pay_complet', { title: '商品列表', hot: results[0].Data, rm: results[1].Data }); }, function (reason) { //console.log(reason); res.render('common/error', {title: '错误', message: reason}); } ); });