反模式:https://efe.baidu.com/blog/promises-anti-pattern/
ES6 Promise:模式与反模式 https://zhuanlan.zhihu.com/p/29783901

  1. 1.Promise 嵌套
  2. // bad
  3. loadSomething().then(function(something) {
  4. loadAnotherthing().then(function(another) {
  5. DoSomethingOnThem(something, another);
  6. });
  7. });
  8. // good
  9. Promise.all([loadSomething(), loadAnotherthing()])
  10. .then(function ([something, another]) {
  11. DoSomethingOnThem(...[something, another]);
  12. });
  13. 2.断开的 Promise 链
  14. // bad
  15. function anAsyncCall() {
  16. var promise = doSomethingAsync();
  17. promise.then(function() {
  18. somethingComplicated();
  19. });
  20. return promise;
  21. }
  22. // good
  23. function anAsyncCall() {
  24. var promise = doSomethingAsync();
  25. return promise.then(function() {
  26. somethingComplicated()
  27. });
  28. }
  29. 3.混乱的集合
  30. // bad
  31. function workMyCollection(arr) {
  32. var resultArr = [];
  33. function _recursive(idx) {
  34. if (idx >= resultArr.length) return resultArr;
  35. return doSomethingAsync(arr[idx]).then(function(res) {
  36. resultArr.push(res);
  37. return _recursive(idx + 1);
  38. });
  39. }
  40. return _recursive(0);
  41. }
  42. 你可以写成:
  43. function workMyCollection(arr) {
  44. return Promise.all(arr.map(function(item) {
  45. return doSomethingAsync(item);
  46. }));
  47. }
  48. 如果你非要以队列的形式执行,你可以写成:
  49. function workMyCollection(arr) {
  50. return arr.reduce(function(promise, item) {
  51. return promise.then(function(result) {
  52. return doSomethingAsyncWithResult(item, result);
  53. });
  54. }, Promise.resolve());
  55. }
  56. 4.catch
  57. // bad
  58. somethingAync.then(function() {
  59. return somethingElseAsync();
  60. }, function(err) {
  61. handleMyError(err);
  62. });
  63. 如果 somethingElseAsync 抛出错误,是无法被捕获的。你可以写成:
  64. // good
  65. somethingAsync
  66. .then(function() {
  67. return somethingElseAsync()
  68. })
  69. .then(null, function(err) {
  70. handleMyError(err);
  71. });
  72. // good
  73. somethingAsync()
  74. .then(function() {
  75. return somethingElseAsync();
  76. })
  77. .catch(function(err) {
  78. handleMyError(err);
  79. });

嵌套promise

:::danger Bad :::

getRes1()
.then(res1 => {
    getRes2(res1)
    .then(res2 => {
        getRes3(res2)
        .then(res3 => {

        })
    })
})

:::success Good :::

getRes1()
.then(res1 => {
    return getRes2(res1)
})
.then(res2 => {
    return getRes3(res2)
})
.then(res3 => {
})

promise 的链式调用体现了 promise 的强大之处,每个函数在上一个 promise 的状态变为 resolved 的时候才会被调用,并且能够得到上一个 promise 的输出结果

promise与数组

不用foreach处理promise,while、for
如果不考虑串行,而是并行的话,最好使用promise.all

链最后加.catch方法

不加 catch() 方法会让回调函数中抛出的异常被吞噬,在你的控制台是看不到相应的错误的,这对调试来说是非常痛苦的。
养成了在自己的 promise 调用链最后添加catch的习惯

回调里显示调用return

最佳实践:在 then 方法内部永远显式的调用 return 或者 throw 的习惯

问:下面四个使用 promise 的语句之间的不同点在哪儿?

#1:正常正确的情况
getRes1().then(function () {
    return getRes2();
});

#2
getRes1().then(functiuoin () {
    getRes2();
});

#3
getRes1().then(getRes2());

#4
getRes1().then(getRes2);

在 then 方法内部,我们可以做三件事:

  1. return 一个 promise 对象
  2. return 一个同步的值或者是 undefined
  3. 同步的 throw 一个错误

1、return 一个 promise 对象:.then的回调里调用promise,但是并没有return的话,值的传递链就会断开,下一个.then回调函数接受到的是undefined 而不是 上一次调用的结果

2、return 一个同步的值或者是 undefined:返回一个同步的值确实是一个将同步代码转化成 promise 风格代码的好方法,这样下一个回调并不关心上层是异步调用还是同步调用,都可以统一在.then里得到上一层的结果值

3、同步的 throw 一个错误:catch() 的回调函数不用关心错误是异步的还是同步的
使用 promise 的时候抛出异常在开发阶段很有用,它能帮助我们定位代码中的错误

#1
getRes1().then(function () {
    return getRes2();// res2
}).then(end);

getRes1
|-----------------|
                  getRes2(undefined)
                  |------------------|
                                     end(res2)
                                     |------------------|
#2
getRes1().then(function () {
    getRes2();
}).then(end);

getRes1
|-----------------|
                  getRes2(undefined)
                  |------------------|
                  end(undefined)
                  |------------------|
# 没有return,下一个.then就变为和上一个并行的啦?
是的,但是又不是完全的 值穿透, end得到的入参是undefined 而不是 res1
#3
getRes1().then(getRes2()).then(end);

getRes1
|-----------------|
getRes2(undefined)
|---------------------------------|
                  end(res1)
                  |------------------|
#4
getRes1().then(getRes2).then(end);

getRes1
|-----------------|
                  getRes2(res1)
                  |------------------|
                                     end(res2)
                                     |------------------|