异步操作 - js [ES6]

异步操作

  • 同时进行多个操作,代码混乱

  • 小例子:回调地狱

同步操作

  • 一次只能进行一个操作

Promise - 封装

let p = new Promise(function(resolve, reject){
  // 异步
  //resolve - 解决
  //reject - 拒绝
   $.ajax({
      url: 'data/1.txt',
      dataType: 'json',
      success(arr){
        resolve(arr)
      },
      error(res){
        reject(res)
      }
   })
})

//第一种
p.then(function(arr){
  alert('成功')
  console.log(arr)
},function(res){
  alert('失败')
  console.log(res)
})

//第二种,必须全部请求成功
Pomise.all([
  p,
  p1,
  ...
]).then(arr=>{
  console.log(arr)
},res=>{
  console.log(res)
})

async/await

  • 普通函数 - 一直执行倒结束

  • async函数 - 能够暂停执行

async function show(){
  let a = 12
  let b = 5
  
  let data = await $.ajax(url: 'data/1.txt', dataType: 'json')
  
  alert(a+b+data[0])
}

show()
posted @ 2021-08-16 16:21  独舟者  阅读(35)  评论(0)    收藏  举报