callback hell

回调地域的产生

  1. $.get(url1, (data1) => {
  2. console.log(data1);
  3. $.get(url2, (data2) => {
  4. console.log(data2);
  5. $.get(url3, (data2) => {
  6. console.log(data3);
  7. // ...
  8. })
  9. })
  10. })

promise链式调用来解决

  1. function loadImg(src) {
  2. return new Promise(
  3. (resolve, reject) => {
  4. const img = document.createElement('img')
  5. img.onload = () => {
  6. resolve(img)
  7. }
  8. img.onerror = () => {
  9. const err = new Error(`图片加载失败 ${src}`)
  10. reject(err)
  11. }
  12. img.src = src
  13. }
  14. )
  15. }
  16. const url1 = 'https://forguo.cn/imgs/logo.png'
  17. const url2 = 'https://forguo.cn/imgs/logo.png'
  18. loadImg(url1).then(img1 => {
  19. console.log(img1.width)
  20. return img1 // 普通对象
  21. }).then(img1 => {
  22. console.log(img1.height)
  23. return loadImg(url2) // promise 实例
  24. }).then(img2 => {
  25. console.log(img2.width)
  26. return img2
  27. }).then(img2 => {
  28. console.log(img2.height)
  29. }).catch(ex => console.error(ex))

手写Promise

应用

封装一个ajax

  1. // ajax封装
  2. const request = function (params) {
  3. return new Promise((resolve, reject) => {
  4. const {
  5. method = 'get',
  6. url,
  7. data
  8. } = params;
  9. const xhr = new XMLHttpRequest();
  10. xhr.open(method, url, true);
  11. xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8')
  12. xhr.onreadystatechange = function () {
  13. /**
  14. * readyState
  15. * 0:还没调用
  16. * 1:载入(正在发送)
  17. * 2:载入完成
  18. * 3:解析响应内容
  19. * 4:解析完成
  20. */
  21. if (xhr.readyState == 4) {
  22. /**
  23. * http状态码
  24. * 2XX 成功返回
  25. * 3XX 重定向
  26. * 4XX 客户端错误
  27. * 5XX 服务端错误
  28. */
  29. if (xhr.status == 200) {
  30. resolve(JSON.parse(xhr.responseText));
  31. } else {
  32. reject(xhr);
  33. }
  34. }
  35. }
  36. xhr.send(JSON.stringify(data) || null);
  37. });
  38. }
  39. let submit = function () {
  40. request({
  41. method: 'post',
  42. url: 'https://forguo.cn/api/common/wechat/sdk',
  43. data: {
  44. url: 'www',
  45. }
  46. }).then(res => {
  47. console.log(res);
  48. }, (err) => {
  49. console.warn(err);
  50. });
  51. }