JS - 承诺 ✅

1. 承诺

承诺代表未来的价值。
国家:

  • 待定
  • 已满足
  • 被拒绝

基本用法

1
getData().then(data => console.log(data));

顺序链接

1
2
step1()
.then(a => step2().then(b => console.log(a,b)));

错误处理

1
2
3
login(null)
.then(msg => console.log(msg))
.catch(err => console.log("Error:",err));

并行执行

1
2
Promise.all([getUsers(),getProducts()])
.then(([u,p]) => console.log(u,p));

直接解析

1
Promise.resolve("Hello").then(console.log);

下一主题: 获取 API & then/catch