JS promise被调用而不被调用 [英] JS promise is getting called without calling it

查看:187
本文介绍了JS promise被调用而不被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么 promise1 一直被呼叫,即使我从未尝试解决它。​​

I don't know why is promise1 keeps getting called even though I never tried to resolve it.

                    function successCallback() {
                        console.log("doSomething func succeeded with sucess");
                    }
                    
                    function failureCallback() {
                        console.log("doSomething func failed with error");
                    }

                    let promis1 = new Promise((res, rej) => {
                    setTimeout(() => {
                        console.log(`Finally got called`);
                        return res(successCallback());
                    }, 5000);
                    });
    
                    function promise2(value) {
                    return new Promise((res, rej) => {
                        console.log(`This is getting called for some reason ${value}`)
                        return res(failureCallback());
                    });
                    }

                    Promise.resolve("6").then(promise2(6));

这是我得到的输出:


由于某种原因而被调用6

This is getting called for some reason 6

doSomething函数因错误而失败

doSomething func failed with error

最后被调用

doSomething func成功成功

doSomething func succeeded with sucess

[完成]在5.525秒内以代码= 0退出

[Done] exited with code=0 in 5.525 seconds


推荐答案

也许这会向您显示代码流

Perhaps this will show you the flow of your code

setTimeout(() => console.log(9)); // 9 will log once all the "synchronous" code below is completed
console.log(1);
let promis1 = new Promise((res, rej) => {
  console.log(2);
  setTimeout(() => {
    console.log(10);
    return res('resolved 1');
  }, 5000);
});
console.log(3);
function promise2(value) {
  console.log(5);
  return new Promise((res, rej) => {
    console.log(6);
    return res('resolved 2');
  });
}
console.log(4);
promise2().then(() => {
  console.log(8);
});
console.log(7);

注意:某些(大多数?)promise实现(包括bluebird)将输出1,2,3,4,5,6,7,9,8,10-因为回调被添加到消息队列的末尾-而在 native 的诺言中, .then 回调跳过队列! (或者说,如今的javascript引擎要比这个简单的模型

note: some (most?) promise implementations (including bluebird) will output 1,2,3,4,5,6,7,9,8,10 - because .then callback is added to the end of the message queue - whereas, it may be the case that in native promises, the .then callback jumps the queue! (or maybe there's more to javascript engines these days than this simple model

这篇关于JS promise被调用而不被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆