Promise.all
这个方法用来一次执行多个promise非常有用。
1 | Promise.all([ |
Promise.resolve
这个方法用来包装同步代码,使之成为一个promise。
1 | Promise.resolve().then(function () { |
Promise执行链
有时候需要一个一个promise顺序执行,下面的技巧可以实现这个想法。
1 | function sequentialize(promiseFactories) { |
Promise.race
这个擅长处理一个定时任务。
1 | Promise.race([ |
Promise.finally
这个方法类似Q.finally,像这样使用:promise.then(...).catch(...).finally(...)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19function finally(promise, cb) {
return promise.then(function (res) {
var promies2 = cb();
if (typeof promise2.then === 'function') {
return promise2.then(function () {
return res;
});
}
return res;
}, function (reason) {
var promise2 = cb();
if (typeof promise2.then === 'function') {
return promise2.then(function () {
return reason;
});
}
return reason;
});
}