Promises

Promise 代表异步操作的最终结果。jQuery 用它自己的方式处理 promises,原生 JavaScript 遵循 Promises/A+ 标准实现了最小 API 来处理 promises。

  • 7.1 done, fail, always

    done 会在 promise 解决时调用,fail 会在 promise 拒绝时调用,always 总会调用。

    1. // jQuery
    2. $promise.done(doneCallback).fail(failCallback).always(alwaysCallback)
    3. // Native
    4. promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)
  • 7.2 when

    when 用于处理多个 promises。当全部 promises 被解决时返回,当任一 promise 被拒绝时拒绝。

    1. // jQuery
    2. $.when($promise1, $promise2).done((promise1Result, promise2Result) => {
    3. });
    4. // Native
    5. Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});
  • 7.3 Deferred

    Deferred 是创建 promises 的一种方式。

    1. // jQuery
    2. function asyncFunc() {
    3. const defer = new $.Deferred();
    4. setTimeout(() => {
    5. if(true) {
    6. defer.resolve('some_value_computed_asynchronously');
    7. } else {
    8. defer.reject('failed');
    9. }
    10. }, 1000);
    11. return defer.promise();
    12. }
    13. // Native
    14. function asyncFunc() {
    15. return new Promise((resolve, reject) => {
    16. setTimeout(() => {
    17. if (true) {
    18. resolve('some_value_computed_asynchronously');
    19. } else {
    20. reject('failed');
    21. }
    22. }, 1000);
    23. });
    24. }
    25. // Deferred way
    26. function defer() {
    27. const deferred = {};
    28. const promise = new Promise((resolve, reject) => {
    29. deferred.resolve = resolve;
    30. deferred.reject = reject;
    31. });
    32. deferred.promise = () => {
    33. return promise;
    34. };
    35. return deferred;
    36. }
    37. function asyncFunc() {
    38. const defer = defer();
    39. setTimeout(() => {
    40. if(true) {
    41. defer.resolve('some_value_computed_asynchronously');
    42. } else {
    43. defer.reject('failed');
    44. }
    45. }, 1000);
    46. return defer.promise();
    47. }