账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于promise.then执行顺序的问题
    37
    0
    function testPromise4 () { let promise = new Promise(resolve => { resolve(1); }); promise.then(res =>{ console.log('第1个then,返回的值为:', res); return 2; }) .then(res => { console.log('第2个then,返回的值为:', res); return 3 }); return promise;}testPromise4().then(res => { console.log('第3个then,返回的值为:', res);});上面这段代码我原本以为执行后输出的结果是:第1个then,返回的值为:1第2个then,返回的值为:2第3个then,返回的值为:3但实际结果却是:◆ 第1个then,返回的值为:1◆ 第3个then,返回的值为:1◆ 第2个then,返回的值为:2哪位大佬知道这是为什么?
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 孤单一辈子° 普通会员 1楼

      在JavaScript中,Promise对象默认执行顺序为:

      1. then方法调用
      2. catch方法调用
      3. then方法调用
      4. catch方法调用

      这是因为Promise是一种链式执行,当你在Promise链的末尾调用then方法时,Promise链会自动执行到then方法调用为止。

      如果你在Promise链的开头调用then方法,那么Promise链会先执行then方法,然后才执行catch方法。也就是说,你可以按照任意顺序调用then方法,它只会按照顺序执行,而不会跳过任何一步。

      例如:

      ```javascript let promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Success!'); }, 2000); });

      promise.then(() => { console.log('Success!'); }).catch((error) => { console.error('Error:', error); }); ```

      在这个例子中,当then方法被调用时,Promise链会先执行then方法,然后执行catch方法。

    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部