Problems in the order of UI rendering and JS execution

<div id="div">
    begin
</div>
<script>
setTimeout(function() {
    alert(" ui  ");
    console.log("timeout1");
    new Promise(function(resolve) {
        console.log("promise3");
        resolve();
        console.log("promise4");
    }).then(function() {
        alert(" uifinally ");
        console.log("then2");
    })
    div.innerHTML = "finally";
})
new Promise(function(resolve) {
    console.log("promise1");
    resolve();
    console.log("promise2");
}).then(function() {
    console.log("then1");
    alert(" ui  ");
})
console.log("global1");
div.innerHTML = "end";
</script>

ui renders innerHTML to end after the first event loop. I can understand why rendering executes before microtasks after entering settimeout

Aug.11,2021

because Promise is an asynchronous operation. Your .then () is essentially a callback callback function. After executing the new Promise (), just return a handle to you, and then continue to execute div.innerHTML = 'finally'; .

js is inherently asynchronous. If you want to follow the normal human brain logic, use async/await to do it. But async is essentially promise

.

although in timeout calls, new promise () is asynchronous in nature. Put with Synchronize, of course, Synchronize executes first. Although promise solves the callback abyss problem, it still performs an asynchronous operation, and .then () returns the result. In addition, you'd better debug the business logic yourself.

Menu