Node.js/Promise:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 标准 == [https://promisesaplus.com/ Promises/A+] 标准。 == 方法 == {| class="wikitable" |- | then || catch || all || race || finally || any |} == 状态 == {| class="wikitable" |- | fulfilled || 已成功 |- | pengding || 进行中 |- | rejected || 已拒绝 |} == 执行状态 == {| class="wikitable" |- | 并行执行 || 顺序执行 || 示例 |} == 封装 == {| class="wikitable" |- | /es6-promise|es6-promise…”
 
Kangkk​(留言 | 贡献)
第41行: 第41行:
| reject || 示例
| reject || 示例
|}
|}
== 并行执行 ==
=== Promise.all ===
通过 Promise.all 处理异常信息。
{{leftrightflex|<syntaxhighlight lang="javascript">
const taskA = new Promise((resolve, reject) =>
  setTimeout(() => resolve(true), 10)
)
  .then(result => result);
const taskB = new Promise((resolve, reject) =>
  setTimeout(() => reject(false), 10)
)
  .then(result => result);
//
Promise.all([taskA, taskB])
  .then(data => console.log(data))
  .catch(e => console.log(e));</syntaxhighlight>|{{consoleout|<pre>false
</pre>}}}}
通过 Promise 任务处理异常信息。
{{leftrightflex|<syntaxhighlight lang="javascript">
const taskA = new Promise((resolve, reject) =>
  setTimeout(() => resolve(true), 10)
)
  .then(result => result)
  .catch(e => e);
//  .then(result => result, error => error);
//
const taskB = new Promise((resolve, reject) =>
  setTimeout(() => reject(false), 10)
)
  .then(result => result)
  .catch(e => e);
//
Promise.all([taskA, taskB])
  .then(data => console.log(data))
  .catch(e => console.log(e));</syntaxhighlight>|{{consoleout|<pre>[ true, false ]
</pre>}}}}


=== 示例 ===
=== 示例 ===

2024年8月7日 (三) 14:12的版本

标准

Promises/A+ 标准。

方法

then catch all race finally any

状态

fulfilled 已成功
pengding 进行中
rejected 已拒绝

执行状态

并行执行 顺序执行 示例

封装

es6-promise 示例 示例
示例 示例 示例
示例 示例 示例

参数

reslove 示例
reject 示例

并行执行

Promise.all

通过 Promise.all 处理异常信息。

模板:Leftrightflex

通过 Promise 任务处理异常信息。

模板:Leftrightflex

示例

标题文字 标题文字 标题文字
习题 示例 示例
示例 示例 示例
示例 示例 示例

传参

1.

promiseDemo.then((result) => {
  console.log(result)
}, (result) => {
  console.log(result)
})

2.

promiseDemo.then((result) => {
  console.log(result)
}).catch((result) => {
  console.log(result)
})

3.

promiseDemo.then((result) => {
  console.log(result)
})   //只接收成功状态

promiseDemo.catch((result) => {
  console.log(result)
})    // 只接收失败状态,可以看成第三种的简写形式

promiseDemo.then(null, (result) => {
  console.log(result)
})   //只接收失败状态

调用

错误链式调用

错误处理机制

实践

使用 try{}catch(){} 捕获 await 抛错