多个成功的 promise 实例,链式调用的规则

249 阅读1分钟

多个成功的 promise 实例,链式调用的规则

  • ⭐️ 如果有多个 fulfilled promise 实例,同时执行 then 链式调用,then 会交替执行,这是编译器的优化,防止一个 promise 占据太久时间
  • ⭐️ then 中返回 promise 实例,相当于多出一个promise 实例,也会遵循"交替执行",但是和直接声明一个 promise 实例,结果有些差异
  • ⭐️ then 中返回 promise 实例,会出现慢两拍的效果(1. promise 由 等待态到成功态; 2. then 函数挂载到 MicroTaskQueue)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 如果有多个 fulfilled promise 实例,同时执行 then 链式调用,then 会交替执行,这是编译器的优化,防止一个 promise 占据太久时间
        Promise.resolve().then(()=>{
            console.log(0);
            // then 中返回 promise 实例,相当于多出一个promise 实例,也会遵循"交替执行",但是和直接声明一个 promise 实例,结果有些差异
            return Promise.resolve(4); // then 中返回 promise 实例,会出现慢两拍的效果(1. promise 由 等待态到成功态; 2. then 函数挂载到 MicroTaskQueue)
        }).then((res)=>{
            console.log(res);
        })

        Promise.resolve().then(()=>{
            console.log(1);
        }).then(()=>{
            console.log(2);
        }).then(()=>{
            console.log(3);
        }).then(()=>{
            console.log(5);
        }).then(()=>{
            console.log(6);
        })
        
        // 控制台输出结果为 0,1,2,3,4,5,6
    </script>
</body>
</html>