why i can't catch error? or how to catch error from this situation?
async function loadscript(js){
let script = document.createElement("script");
script.src = js;
document.body.append(script);
try {
script.onload = () => {
console.log(add(4,8));
}
script.onerror = () => {
throw new Error("cant load resources");
}
} catch(err) {
console.log(err);
}
}
loadscript("calcc.js");
i saw code where u must check in onl oad if response ok and there was not used "script.onerror" .. why? is it possible to use one rror not check "response.ok" ?
why try catch works with async await but not with promise?
why script.onload don't need "await" keyword like script.onload = await ()=>{}
CodePudding user response:
You might want to wrap the try catch clause inside the one rror callback:
function loadscript(js) {
return new Promise((r,e) => {
const script = document.createElement("script");
script.onload = () => {
console.log($ && "Loaded jQuery");
r();
}
script.onerror = () => {
try {
throw new Error("cant load resource" js);
} catch (e) {
console.log(e.message)
}
r();
}
script.src = js;
document.body.append(script);
});
}
(async() => {
await loadscript("notexisiting.jquery.min.js");
await loadscript("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js");
})()
CodePudding user response:
In javascript you can handle asynchronous events in several ways: callbacks and promises. Async/await it is syntactic sugar for promises and async function return promise. You can't using try/catch with callbacks for handling errors like one rror callback. If you want to using try/catch blocks with async api first you need to wrap your callback api to promise api like this, for example:
function loadScript(src) {
return new Promise((res, rej) => {
const script = document.createElement("script");
script.src = src;
script.onload = () => res();
script.onerror = err => rej(err);
});
}
(async () => {
try {
await loadScript("somePath");
// after this line your script is loaded
} catch (err) {
// or, if promise rejected
// handle error
}
})();