使用promise简单封装express的请求request

代码如下:

const request = require('request');

function reqPme(options) {
  return new Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (error) {
        reject(error);
      }
      resolve(body);

    })
  }).catch(error => console.log('caught', error));  //捕获异常



}
module.exports = reqPme;

然后使用 async…await

let reqPme = require('./pme_request');//引入封装的模块

let op1,op2.....;//地址参数

router.get('/', function (req, res, next) {
  async function implement() {
        
        rest_1=await reqPme(op1);
        groupCourseClass=rest_1.data;

        rest_2=await reqPme(op2);
        groupAddress=rest_2.data;

        rest_3=await reqPme(op3);
        groupHotCourses=rest_3.data;

        rest_4=await reqPme(op4);
        groupCoursesList=rest_4.data;
        groupCoursePage=rest_4.page;

        res.render('discoutcourse', { 
            title: '优惠团课', 
            pageIndex: 3,
            groupCourseClass,
            groupAddress,
            groupHotCourses,
            groupCoursesList,
            groupCoursePage
        });
    }
    });
    implement().catch(error => console.log(error.message)); //

async 函数也是返回一个promise,所以也要捕获一下

你可能感兴趣的:(node,node,express,promise,request,异步处理)