JavaScript实现同步Ajax请求的两种方式

JavaScript的Ajax请求默认是异步的,有以下两种方式能让Ajax请求变成同步

方式一

使用ES7的Async和Await

async function main(){
   
  const env = await queryEnv('141001')
  console.log(env)
}

async function queryEnv (platform) {
   
  const result = await axios({
   
    url: '/chronic/userPlatformConfig/getBaseInfo',
    params: {
    platform: platform },
    method: 'post',
    headers: {
   
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
  return result
}

main()

方式二

使用原生的XmlHttpRequest发送同步请求,xhr.open的第三个参数为false表示同步请求

function main () {
   
  const env = queryEnv('141001')
  console.log(env)
}

function queryEnv (platform) {
   
  const xhr = new XMLHttpRequest()
  const url = '/chronic/userPlatformConfig/getBaseInfo'
  xhr.open('post', url, false) // 同步请求
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  xhr.send('platform=' + platform)
  const res = JSON.parse(xhr.responseText)
  return res.body
}

main()

比较

方式一使用ES7的语法Async/Await将本来是异步的Ajax请求转换成同步的请求,方式二本身就是同步请求。

方式一不好的地方是若queryEnv这个函数被嵌套多层调用,每个调用的地方都要加上Async/Await,被多层嵌套时,代码阅读和debug都有不方便。
好处是queryEnv这个函数可以随时在同步异步间进行转换,上述示例是同步函数,若要转换成异步,使用then即可。

function main(){
   
  queryEnv('141001').then(env => {
   
	console.log(env)
  })
}

方式二的好处是调用放的代码逻辑写起来很顺畅,方便阅读,不怕多层嵌套;但不能像方式一那样同步异步转换,若要转换需要再加个函数或者是增加是否异步这个参数。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务