要是实在不知道要干什么,那就喝两杯思路就来了!

导航菜单

JavaScript中回调函数

既然Promise可以链式调用,例如p.then( ).then()....这样,就意味着它肯定会返回一个Promise对象。如果我们是手动再返回了一个新的Promise对象,那么下一个then方法就是新的Promise中的对象的方法了,是代表新的Promise对象状态改变后的回调函数,而不是前一个,p.then( ).then( )这样调用的话,第二个then需要判断新的Promise状态是否改变才决定是否调用;then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为Resolved时调用,第二个回调函数是Promise对象的状态变为Reject时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。

  1. // Promise方法的使用
  2.  
  3. function build (floor) {
  4. return new Promise(function (resolve, reject) {
  5. if (typeof floor === 'number') {
  6. resolve(floor);
  7. } else {
  8. reject(floor + ' 异常参数值。');
  9. }
  10. })
  11. }
  12.  
  13. build(0).then(function (res) {
  14. console.log(res + '=> 还在外面');
  15. return res + 1;
  16. }).then(function (res) {
  17. console.log(res + '=> 进入一层');
  18. return res + 1;
  19. }).then(function (res) {
  20. console.log(res + '=> 上到二层');
  21. return res + 1;
  22. }).then(function (res) {
  23. console.log(res + '=> 上到三层');
  24. return res + 1;
  25. }).then(function (res) {
  26. console.log(res + '=> 上到四层');
  27. }).catch(function (res) {
  28. console.log(res + '系统已锁死!');
  29. })
  30. // 普通回调函数示例
  31.  
  32. var t = 0;
  33.  
  34. function parFun (fn) {
  35. setTimeout(function () {
  36. += 10;
  37. fn && typeof fn === 'function' && fn();
  38. })
  39. }
  40.  
  41. parFun(function () {
  42. console.log(t);
  43. })


发表评论