Is it safe to assume that the async
function will release the execution in the order it was initiated?
For instance, consider this code snippet:
class Bar {
public barPromise = new Promise(resolve => setTimeout(resolve, 1000));
public data = null;
public async setData(d) {
await this.barPromise;
this.data = d;
}
}
async function initialize() {
const bar = new Bar();
bar.setData(1);
bar.setData(2);
bar.setData(3);
await bar.barPromise;
console.log(bar.data);
}
initialize();
Would it be reasonable to expect the output to be 3
? It's important to note that the initialize()
function doesn't pause during calls to bar.setData(x)
. Instead, it continues until waiting for the resolution of the promise with await bar.barPromise
, resulting in multiple awaits waiting for bar.barPromise
to resolve.
This example serves merely as a demonstration. In practical scenarios, I would avoid using such patterns. In my circumstances, I rely on a third-party library that initializes at some point, and I want users of my class to perceive it as synchronous so they can safely invoke methods whenever needed, assured that the outcome will be consistent. Therefore, if a setting is updated twice, only the last value will persist.