简体   繁体   中英

Why function block promise in redux-react Action?

    getApplication(){
    function a() {
        let time = +new Date();
        while (time + 10000 > +new Date()) {
            console.log(1);
        }
    }

    return (dispatch)=> {
        httpUtil.GET(url).then(
            (data)=> {
                console.log(data);
            },
            (err)=> {});
        a();
    };
}

In redux Action asynchronize Action Creator, httpUtil.GET will return API response from web-end, however, under my test, it was blocked by function a , each time httpUtil.GET returned after a excuted completely.

httpUitl is based on fetch .

why promise was blocked by function a ?

When a JavaScript Promise resolves/rejects, the relevant callbacks from .then() / .catch() get added to the queue for the event loop , the same as setTimeout , setInterval , or anything else asynchronous in JavaScript.

The thing that's important to realize about the event loop is that it doesn't start processing messages off the queue until the stack has fully cleared - which usually doesn't happen until the outermost function that's currently executing finishes. Because a() is synchronous, getApplication() can't return until it finishes, which means in turn that whatever called getApplication() can't return until that finishes, and so on.

So in other words - the promise itself is resolving before a() , but the JavaScript engine isn't able to run your callback until a() finishes and the stack can clear.

I'd encourage you to watch the talk "What the heck is the event loop anyway?" if you want to learn more - it'll really help your understanding of how JavaScript works under the hood.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM