promise

promise用来解决回调地狱的问题

支持promise,就意味着可以使用.then方法来使用回调函数

.then方法有两个参数,第一个是成功的回调,第二个是失败的回调

promise对象有.then方法,可以用来传递回调函数

使用promise方法封装ajax请求

function ajax(option){
return new Promise((resolve,reject)=>{
  let xhr=new XMLHttpRequest()
  xhr.open(option.type,option.url)
  xhr.send(null)
  xhr.onreadystatechange=function(){
    if(xhr.readyState===4){
      if(xhr.status===200){
        resolve(xhr.response|ext)
      }else{
        reject()
      }
    }
  }
})
}

使用promise封装一个方法

function timeout(time){
  return new Promise((resolve,reject)=>{
    setTimeout(function(){
  resolve()
    },time)
  })
}
timeout(5000).then(function(){
  console.log('5s后执行的操作')
})

.then的连写方法,需要在回调函数中,返回一个新的promise对象

function timeout(time){
  return new Promise((resolve,reject)=>{
    setTimeout(function(){
  resolve()
    },time)
  })
}
timeout(1000).then(function(){
  console.log('1s后执行的操作')
  return  timeout(1000)
}).then(function(){
  console.log('2s后执行的操作')
  return  timeout(1000)
}).then(function(){
  console.log('3s后执行的操作')
} 
)

promise的静态方法

promise.all 在所有的promise异步操作完成之后,执行某个任务,就可以使用

function timeout(time){
  return new Promise((resolve,reject)=>{
    setTimeout(function(){
      console.log(time+'异步操作完成了')
  resolve()
    },time)
  })
}
 let arr=[timeout(1000),timeout(3000),timeout(5000)]
Promise.all(arr).then(function(){
  console.log('所有的异步操作完成了')
})

promise.race 在第一个promise异步操作完成之后,就执行某个任务

function timeout(time){
  return new Promise((resolve,reject)=>{
    setTimeout(function(){
      console.log(time+'异步操作完成了')
  resolve()
    },time)
  })
}
 let arr=[timeout(1000),timeout(3000),timeout(5000)]
Promise.race(arr).then(function(){
  console.log('某个的异步操作先完成了')
})

 

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...