"chrome: invoking 'alert()' during microtask execution is deprecated and will be removed" Code Answer

5

yes, the warning is justified: you're calling alert within a microtask, in this case a promise completion. (see difference between microtask and macrotask within an event loop context.)

alert, prompt, and confirm are relics of an age long past, and they have a problem: they completely interrupt the normal workings of javascript and arguably violate its run-to-completion semantics by completely suspending execution, right in the middle of a job from the job queue (or a task from the event loop; javascript and the html5 spec differ on terminology) and do ui in the form of a blocking modal. this is just not in keeping with the general mode of interaction, which is event-based (show the message, get an event when it's closed).

you can work around it by doing the alert in a macrotask instead:

this.service.uploadfile((error: any) => {
    if (error) {
        settimeout(() => {
            console.log(error);
            alert("an error occured");
        }, 0);
        return;
    }

    this.onuploadcompleted()
});

...but really the solution is to stop using alert, prompt, and confirm entirely.


here's a fun example of micro and macro tasks: a promise completion is a microtask, whereas timer callbacks are macrotasks. the initial run of the script is also a macrotask, as is a dom event callback. all of the microtasks queued by a macrotask are run before the next macrotask is run; e.g., they jump the queue. so with this:

// first, we set a timer callback for 0ms
settimeout(() => {
  console.log("timer fired");
}, 0);

// now we get a promise that's *already* resolved and hook a callback
promise.resolve().then(() => {
  console.log("promise resolved");
});

// now show a message demonstrating we got here before the promise resolution callback
console.log("got to the end");

...we see

got to the end
promise resolved
timer fired

...rather than

got to the end
timer fired
promise resolved

....which we would have gotten if all tasks were created equal.

By Zeeshan Hussain on March 13 2022

Answers related to “chrome: invoking 'alert()' during microtask execution is deprecated and will be removed”

Only authorized users can answer the Search term. Please sign in first, or register a free account.