Promise 解决同步请求问题


  在写小程序和vue项目中,由于 api 不提供 同步请求,因此,可以通过  Promise 来实现 同步请求操作

 在这里 对于 Promise 不太了解的小伙伴 可以查找 Promise 的api 文档

  下面是主要代码

const axios = require('axios')
function axiosPro(axiosArgs) {
  const { method, url, data, params, headers, responseType } = axiosArgs
  return new Promise(function (resolve, reject) {
    axios({
      method: method,
      url: url,
      data: data,
      params: params,
      headers: headers,
      responseType: responseType
    }).then(function (ret) {
      resolve(ret);
    }).catch(function (err) {
      reject(err);
    })
  })
};

引用
module.exports = async ctx => {
  const ret = await axiosPro(ctx.request.body)
  console.log(ret.data)//同步输出结果
  ctx.body = ret.data
}

    

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM