Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise execute order is not same as browser and Node.js #684

Open
zizifn opened this issue Jan 13, 2025 · 1 comment
Open

Promise execute order is not same as browser and Node.js #684

zizifn opened this issue Jan 13, 2025 · 1 comment

Comments

@zizifn
Copy link

zizifn commented Jan 13, 2025

Background

Promise queue or Microtask queue will exhausted in the end of each event callback.

Code

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
xhr.addEventListener("readystatechange", () => {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log('readystatechange1', JSON.parse(xhr.responseText));
        Promise.resolve("readystatechange1->promise1").then(console.log);
    }
});
xhr.addEventListener("readystatechange", () => {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log('readystatechange2', JSON.parse(xhr.responseText));
        Promise.resolve("readystatechange2->promise2").then(console.log);
    }
});
xhr.send();

Browser

readystatechange1 {userId: 1, id: 1, title: 'delectus aut autem', completed: false}
readystatechange1->promise1
readystatechange2 {userId: 1, id: 1, title: 'delectus aut autem', completed: false}
readystatechange2->promise2

txiki.js

readystatechange1 {
 userId: 1,
  id: 1,
  title: 'delectus aut autem',
  completed: false
}
readystatechange2 {
 userId: 1,
  id: 1,
  title: 'delectus aut autem',
  completed: false
}
readystatechange1->promise1
readystatechange2->promise2

I'm not very familiar with txiki.js or libuv, but I think it might be because txiki.js executes promise jobs in the uv_check phase, meaning promise jobs run in each loop iteration rather than after each event callback.

@zizifn zizifn changed the title Promise executed order is not same as browser and Node.js Promise execute order is not same as browser and Node.js Jan 13, 2025
@saghul
Copy link
Owner

saghul commented Jan 13, 2025

A tricky one! Thanks for the report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants