Node.js/Promise:修订间差异
来自康健生活
< Node.js
创建页面,内容为“== 标准 == [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…” |
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” 标签:ReplaceText 移动版编辑 移动版网页编辑 |
||
| (未显示同一用户的8个中间版本) | |||
| 第19行: | 第19行: | ||
|} | |} | ||
== | == 方法 == | ||
=== Promise.race === | |||
== | == 串行执行 == | ||
=== 预设数据 === | |||
假设存在两个任务 taskA 和 taskB。 | |||
=== | |||
=== | <syntaxhighlight lang="javascript"> | ||
{| | function taskA (data){ | ||
|- | console.log('pre-data', data); | ||
return new Promise(function(resolve, reject){ | |||
|- | setTimeout(() => resolve(true), 10); | ||
| [[/ | }); | ||
|- | } | ||
| | function taskB (data){ | ||
|- | console.log('pre-data', data); | ||
| | return new Promise(function(resolve, reject){ | ||
setTimeout(() => reject(false), 10); | |||
}); | |||
}</syntaxhighlight> | |||
== 链式执行 == | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
Promise.resolve() | |||
.then(function(){ | |||
return taskA(); | |||
}) | |||
.then(function(data){ | |||
console.log(data); | |||
}) | |||
.then(function(){ | |||
return taskB(); | |||
}) | |||
.then(function(data){ | |||
console.log(data); | |||
}) | |||
.catch(e => console.log(e));</syntaxhighlight>|{{consoleout|<pre>true | |||
false | |||
</pre>}}}} | |||
=== 队列执行 === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const queue = arr => { | |||
let sequence = Promise.resolve(); | |||
arr.forEach(function (item) { | |||
sequence = sequence.then(item); | |||
}); | |||
return sequence; | |||
} | |||
// | |||
queue([taskA, taskB]) | |||
.then(data => console.log(data)) | |||
.catch(e => console.log(e));</syntaxhighlight>|{{consoleout|<pre>pre-data undefined | |||
pre-data true | |||
false | |||
</pre>}}}} | |||
其他 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
function queue(arr) { | |||
return arr.reduce((a, b) => { | |||
a = a.then(b) | |||
return a | |||
}, Promise.resolve()); | |||
} | |||
// | |||
queue([taskA, taskB]) | |||
.then(data => console.log(data)) | |||
.catch(e => console.log(e));</syntaxhighlight>|{{consoleout|<pre>pre-data undefined | |||
pre-data true | |||
false | |||
</pre>}}}} | |||
=== 同步编程 === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
async function queue(arr) { | |||
let res = null | |||
for (let promise of arr) { | |||
res = await promise(res) | |||
} | |||
return await res | |||
} | |||
// | |||
queue([taskA, taskB]) | |||
.then(data => console.log(data)) | |||
.catch(e => console.log(e));</syntaxhighlight>|{{consoleout|<pre>pre-data null | |||
pre-data true | |||
false | |||
</pre>}}}} | |||
=== 中断 === | |||
中断机制,利用 Promise 链的异常捕获机制的特性。当抛出一个错误时,错误信息沿着链路向后传递。这里我们可以通过异常捕获达到终止传递的目的。 | |||
在异常传递的链的终点进行捕获 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
Promise.resolve() | |||
.then((onFulfilled, onRejected) => { | |||
console.log('NO1:', onFulfilled); | |||
throw 'throw on onFulfilled'; | |||
}) | |||
.then((onFulfilled, onRejected) => console.log('NO2:', onFulfilled)) | |||
.catch(e => console.log('catch:', e));</syntaxhighlight>|{{consoleout|<pre>NO1: undefined | |||
catch: throw on onFulfilled | |||
</pre>}}}} | |||
在异常传递的链的下一级进行捕获 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
Promise.resolve() | |||
.then((onFulfilled, onRejected) => { | |||
console.log('NO1:', onFulfilled); | |||
throw 'throw on onFulfilled'; | |||
}) | |||
.then( | |||
(onFulfilled, onRejected) => console.log('NO2:', onFulfilled), | |||
e => console.log('NO2:', e) | |||
) | |||
.catch(e => console.log('catch:', e));</syntaxhighlight>|{{consoleout|<pre>NO1: undefined | |||
NO2: throw on onFulfilled | |||
</pre>}}}} | |||
其他 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
Promise.resolve() | |||
.then(() => { | |||
console.log('NO1'); | |||
// 返回 pending 状态的 Promise 对象,执行链被终止。 | |||
return new Promise(()=>{}); | |||
}) | |||
.then(() => { | |||
console.log('NO2'); | |||
}) | |||
.catch(err => { | |||
console.log('catch:', err); | |||
});</syntaxhighlight>|{{consoleout|<pre>NO1 | |||
</pre>}}}} | |||
== 并行执行 == | |||
=== Promise.all === | |||
通过 Promise.all 处理异常信息。 | |||
{{Double-columns|<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 任务处理异常信息。 | |||
{{Double-columns|<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>}}}} | |||
== es6 == | |||
<syntaxhighlight lang="javascript"> | |||
var axios = require('axios'); | |||
var Promise = require('es6-promise').Promise; | |||
module.exports = function(opts, request) { | |||
return new Promise(function(resolve, reject) { | |||
axios(opts).then(function(res) { | |||
res = res.data | |||
if (res.success) { | |||
resolve(res) | |||
} else { | |||
reject({ ___req: opts, ___res: res }) | |||
} | |||
}).catch(function(err) { | |||
reject({ ___req: opts, ___res: err.data || err.stack || err }) | |||
}) | |||
}) | |||
}</syntaxhighlight> | |||
== 示例 == | |||
== 习题 == | |||
判断输出以及相应的时间 | |||
<syntaxhighlight lang="javascript"> | |||
let doSth = new Promise((resolve, reject) => { | |||
console.log('hello'); | |||
resolve(); | |||
}); | |||
setTimeout(() => { | |||
doSth.then(() => { | |||
console.log('over'); | |||
}) | |||
}, 10000);</syntaxhighlight> | |||
判断输出顺序 | |||
<syntaxhighlight lang="javascript"> | |||
setTimeout(function() { | |||
console.log(1) | |||
}, 0); | |||
new Promise(function executor(resolve) { | |||
console.log(2); | |||
for( var i=0 ; i<10000 ; i++ ) { | |||
i == 9999 && resolve(); | |||
} | |||
console.log(3); | |||
}).then(function() { | |||
console.log(4); | |||
}); | |||
console.log(5);</syntaxhighlight> | |||
== 传参 == | == 传参 == | ||
2026年11月26日 (四) 08:37的最新版本
标准
Promises/A+ 标准。
方法
| then | catch | all | race | finally | any |
状态
| fulfilled | 已成功 |
| pengding | 进行中 |
| rejected | 已拒绝 |
方法
Promise.race
串行执行
预设数据
假设存在两个任务 taskA 和 taskB。
function taskA (data){
console.log('pre-data', data);
return new Promise(function(resolve, reject){
setTimeout(() => resolve(true), 10);
});
}
function taskB (data){
console.log('pre-data', data);
return new Promise(function(resolve, reject){
setTimeout(() => reject(false), 10);
});
}
链式执行
Promise.resolve()
.then(function(){
return taskA();
})
.then(function(data){
console.log(data);
})
.then(function(){
return taskB();
})
.then(function(data){
console.log(data);
})
.catch(e => console.log(e));
true false
队列执行
const queue = arr => {
let sequence = Promise.resolve();
arr.forEach(function (item) {
sequence = sequence.then(item);
});
return sequence;
}
//
queue([taskA, taskB])
.then(data => console.log(data))
.catch(e => console.log(e));
pre-data undefined pre-data true false
其他
function queue(arr) {
return arr.reduce((a, b) => {
a = a.then(b)
return a
}, Promise.resolve());
}
//
queue([taskA, taskB])
.then(data => console.log(data))
.catch(e => console.log(e));
pre-data undefined pre-data true false
同步编程
async function queue(arr) {
let res = null
for (let promise of arr) {
res = await promise(res)
}
return await res
}
//
queue([taskA, taskB])
.then(data => console.log(data))
.catch(e => console.log(e));
pre-data null pre-data true false
中断
中断机制,利用 Promise 链的异常捕获机制的特性。当抛出一个错误时,错误信息沿着链路向后传递。这里我们可以通过异常捕获达到终止传递的目的。
在异常传递的链的终点进行捕获
Promise.resolve()
.then((onFulfilled, onRejected) => {
console.log('NO1:', onFulfilled);
throw 'throw on onFulfilled';
})
.then((onFulfilled, onRejected) => console.log('NO2:', onFulfilled))
.catch(e => console.log('catch:', e));
NO1: undefined catch: throw on onFulfilled
在异常传递的链的下一级进行捕获
Promise.resolve()
.then((onFulfilled, onRejected) => {
console.log('NO1:', onFulfilled);
throw 'throw on onFulfilled';
})
.then(
(onFulfilled, onRejected) => console.log('NO2:', onFulfilled),
e => console.log('NO2:', e)
)
.catch(e => console.log('catch:', e));
NO1: undefined NO2: throw on onFulfilled
其他
Promise.resolve()
.then(() => {
console.log('NO1');
// 返回 pending 状态的 Promise 对象,执行链被终止。
return new Promise(()=>{});
})
.then(() => {
console.log('NO2');
})
.catch(err => {
console.log('catch:', err);
});
NO1
并行执行
Promise.all
通过 Promise.all 处理异常信息。
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));
false
通过 Promise 任务处理异常信息。
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));
[ true, false ]
es6
var axios = require('axios');
var Promise = require('es6-promise').Promise;
module.exports = function(opts, request) {
return new Promise(function(resolve, reject) {
axios(opts).then(function(res) {
res = res.data
if (res.success) {
resolve(res)
} else {
reject({ ___req: opts, ___res: res })
}
}).catch(function(err) {
reject({ ___req: opts, ___res: err.data || err.stack || err })
})
})
}
示例
习题
判断输出以及相应的时间
let doSth = new Promise((resolve, reject) => {
console.log('hello');
resolve();
});
setTimeout(() => {
doSth.then(() => {
console.log('over');
})
}, 10000);
判断输出顺序
setTimeout(function() {
console.log(1)
}, 0);
new Promise(function executor(resolve) {
console.log(2);
for( var i=0 ; i<10000 ; i++ ) {
i == 9999 && resolve();
}
console.log(3);
}).then(function() {
console.log(4);
});
console.log(5);
传参
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 抛错
No categories