Skip to content

Commit

Permalink
Correct mistake in post: javascript-promise-tricks
Browse files Browse the repository at this point in the history
  • Loading branch information
AleksandrHovhannisyan committed Aug 1, 2021
1 parent 3a3275e commit f8e1dd6
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/_posts/2020-09-12-javascript-promise-tricks.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,26 +237,28 @@ The naive approach uses nested `onload` handlers, like so:

{% include codeHeader.html %}
```javascript
const script1 = document.createElement('script');
const script2 = document.createElement('script');
script2.src = 'two.js';
const script3 = document.createElement('script');

document.body.appendChild(script1);
document.body.appendChild(script2);
document.body.appendChild(script3);

script2.onload = () => {
console.log('two.js loaded');
const script1 = document.createElement('script');
script1.src = 'one.js';
document.body.appendChild(script1);

script1.onload = () => {
console.log('one.js loaded');
const script3 = document.createElement('script');
script3.src = 'three.js';
document.body.appendChild(script3);

script3.onload = () => {
console.log('three.js loaded');
};
};

script2.src = 'two.js';
script1.src = 'one.js';
script3.src = 'three.js';
};
```

Expand All @@ -265,9 +267,9 @@ script2.onload = () => {
That works, and we'll get this output:

```plaintext
index.js:6 two.js loaded
index.js:12 one.js loaded
index.js:18 three.js loaded
two.js loaded
one.js loaded
three.js loaded
```

But the nesting only gets worse from here, and there's already a lot of hard-coded repetition.
Expand All @@ -278,7 +280,6 @@ Instead, we can use Promises to regulate the order in which our scripts are load
```javascript
function loadScript(url) {
const script = document.createElement('script');
script.src = url;
document.body.appendChild(script);

return new Promise((resolve, reject) => {
Expand All @@ -290,6 +291,9 @@ function loadScript(url) {
script.onerror = () => {
reject(`Error loading script at ${url}`);
};

// Important to set the src after registering the onload listener
script.src = url;
});
}
```
Expand Down

0 comments on commit f8e1dd6

Please sign in to comment.