axios一般是作为异步请求使用的,但是某种特殊情况下需要同步请求,如何实现呢?

首先定义一个方法syncAxios

let axios = require('axios');

exports.syncAxios = function (obj = {}) {
  let url =  "http://www.rrbay.com/api/";

  return  new    Promise((resolve, reject) => {
    axios(url, {
      method: 'POST',
      timeout: 5000,
      params: {
        sProcName: obj.sProcName,
        idNo: obj.id,
        userName: obj.qq,
        overTime: obj.endTime
      }
    }).then((res) => {
      resolve(res.data);
    }).catch((error) => {
      reject(error)
    })
  })
};

然后在controllers 调用

exports.check = function (req, res) {
  //定义async方法体
  XXXMode.findById(id).populate('author').exec(async function (err, result) { 
    let dataCode = false;
    if(result.status ==0){
        //同步调用
      await baseapi.syncAxios({
          sProcName: 'Update',
          id: '000000-1111-2222-3333-9999999',
          qq: '391502069',//result.author.name,
          endTime:  '2022/12/31 11:39:05'//result.EndTime
        }).then((data) => {
          console.log(data, 'res');
        }).catch((err) => {
          console.log(err && err.stack);
        });

    }
    result.save(function (err, onewxtob) {
      if (req.xhr) {
        return res.json({
          status: !err
        })
      }
    });
  });
};

view中使用模板引擎jade,需要在请求check后,延迟刷新页面显示请求结果

setTimeout(function () {
   $(location).attr('href',window.location.href)
}, 1000)

标签:nodejs express axios async await jade