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 题目 4 - 3 #136

Open
leslie1943 opened this issue Jan 10, 2021 · 0 comments
Open

异步编程-Promise 题目 4 - 3 #136

leslie1943 opened this issue Jan 10, 2021 · 0 comments

Comments

@leslie1943
Copy link
Owner

Promise 4 - 3

  • 使用.race()方法, 它只会获取最先执行完成的那个结果, 其它的异步任务虽然也会继续进行下去, 不过race已经不管那些任务的结果了.
function runAsync (x) {
  const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
  return p
}
Promise.race([runAsync(1), runAsync(2), runAsync(3)])
  .then(res => console.log('result: ', res))
  .catch(err => console.log(err))
// 1
// 'result: ' 1
// 2
// 3
  • 这个race有什么用呢?使用场景还是很多的, 比如我们可以用 race 给某个异步请求设置超时时间, 并且在超时后执行相应的操作
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant