理解Promise为什么这样设计,为了解决什么问题

    1. // Promise()同步 executor 同步
    2. const p = new Promise((resolve, reject) => {})
    3. // 异步
    4. p.then((res) => {})

    Q: 为什么Promise执行时同步,p.then异步?

    1. $.ajax({
    2. url: 'xxx',
    3. success(data) {
    4. console.log(getNames(data)); // ['zhangsan','lisi']
    5. }
    6. })
    7. console.log('1111');
    8. function getNames(data) {
    9. return data.map(funciton(item){
    10. return item.name
    11. })
    12. }
    13. // 打印结果:
    14. 1111
    15. ['zhangsan','lisi']
    16. $.ajax({}) 异步程序
    17. 与console.log('1111'); 无关系
    18. ====================================================================
    19. var data = $.ajax({
    20. url: 'xxx',
    21. async: false // 同步
    22. })
    23. console.log(getNames(data)); // 与ajax为同步关系
    24. console.log('1111'); // 与ajax为同步关系
    25. function getNames(data) {
    26. return data.map(funciton(item){
    27. return item.name
    28. })
    29. }
    30. // 打印结果:
    31. ['zhangsan','lisi']
    32. 1111

    Promise 异步问题同步化解决方案

    1. const p = new Promise((resolve, reject) => {
    2. //同步
    3. $.ajax({
    4. url: 'xxx',
    5. success(data) {
    6. resolve(data);
    7. }
    8. })
    9. })
    10. // 异步,不阻塞下面程序运行
    11. p.then((res) => {
    12. console.log(getNames(data));
    13. })
    14. console.log('1111');
    15. function getNames(data) {
    16. return data.map(funciton(item){
    17. return item.name
    18. })
    19. }
    20. // 打印结果:
    21. 1111
    22. ['zhangsan','lisi']

    异步程序通过包裹一个Promise, 然后通过then拿到异步结果,且不阻塞其他程序

    1. function getData() {
    2. return new Promise((resolve, reject) => {
    3. $.ajax({
    4. url: 'xxx',
    5. success(data) {
    6. resolve(data);
    7. }
    8. })
    9. })
    10. }
    11. async function doSth() {
    12. const data = await getData();
    13. console.log(getNames(data));
    14. }
    15. console.log('1111');
    16. function getNames(data) {
    17. return data.map(funciton(item){
    18. return item.name
    19. })
    20. }
    21. // 打印结果:
    22. 1111
    23. ['zhangsan','lisi']