Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise.all 和 Promise.race 的区别 #34

Open
songning0605 opened this issue Aug 31, 2020 · 0 comments
Open

Promise.all 和 Promise.race 的区别 #34

songning0605 opened this issue Aug 31, 2020 · 0 comments
Labels

Comments

@songning0605
Copy link
Owner

songning0605 commented Aug 31, 2020

参考:理解和使用Promise.allPromise.race

Pomise.all

Promise.all()方法用于将多个Promise实例,包装成一个新的Promise实例。

const p = Promise.all([p1, p2, p3]);
  • Promise.all()成功和失败的返回值是不同的,成功的时候返回的是一个结果数组,而失败的时候则返回最先被reject的值。
let p1 = new Promise((resolve, reject) => {
  resolve('成功了')
})

let p2 = new Promise((resolve, reject) => {
  resolve('success')
})

let p3 = Promse.reject('失败')

Promise.all([p1, p2]).then((result) => {
  console.log(result)               //['成功了', 'success']
}).catch((error) => {
  console.log(error)
})

Promise.all([p1,p3,p2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error)      // 失败了,打出 '失败'
})
  • Promise.all()的结果是成功时,返回结果的数组里边的数据顺序和Promise.all()接收到的Promise顺序是一致的。

Promise.race的使用

顾名思义,Promse.race就是赛跑的意思,意思就是说,Promise.race([p1, p2, p3])里面哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态,其他Promise的代码还会执行,只是不会返回。

let p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  },1000)
})

let p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('failed')
  }, 500)
})

Promise.race([p1, p2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error)  // out 'failed'
})
@songning0605 songning0605 changed the title Promise.all 和 Promise.race 的区别 Promise.allPromise.race 的区别 Aug 31, 2020
@songning0605 songning0605 changed the title Promise.allPromise.race 的区别 Promise.all 和 Promise.race 的区别 Aug 31, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant