You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Now the unhandled rejction appears again. Why? Because `unhandledrejection` triggers when the microtask queue is complete. The engine examines promises and, if any of them is in "rejected" state, then the event is generated.
175
+
176
+
In the example above `setTimeout` adds the `.catch`, and it triggers too, of course it does, but later, after the event has already occured.
177
+
129
178
## Summary
130
179
131
180
- Promise handling is always asynchronous, as all promise actions pass through the internal "promise jobs" queue, also called "microtask queue" (v8 term).
132
181
133
182
**So, `.then/catch/finally` is called after the current code is finished.**
134
183
135
-
If we need to guarantee that a piece of code is executed after `.then/catch/finally`, it's best to add it into a chained `.then` call.
184
+
If we need to guarantee that a piece of code is executed after `.then/catch/finally`, it's best to add it into a chained `.then` call.
136
185
137
186
- There's also a "macrotask queue" that keeps various events, network operation results, `setTimeout`-scheduled calls, and so on. These are also called "macrotasks" (v8 term).
Copy file name to clipboardExpand all lines: 6-binary/04-file/article.md
+15-1
Original file line number
Diff line number
Diff line change
@@ -102,5 +102,19 @@ Reading methods `read*` do not generate events, but rather return the result, as
102
102
That's only inside a Web Worker though, because delays and hang-ups in Web Workers are less important, they do not affect the page.
103
103
```
104
104
105
+
## Summary
105
106
106
-
It most often used to read from files, and
107
+
`File` object inherit from `Blob`.
108
+
109
+
In addition to `Blob` methods and properties, `File` objects also have `fileName` and `lastModified` properties, plus the internal ability to read from filesystem. We usually get `File` objects from user input, like `<input>` or drag'n'drop.
110
+
111
+
`FileReader` objects can read from a file or a blob, in one of three formats:
112
+
- String (`readAsText`).
113
+
- `ArrayBuffer` (`readAsArrayBuffer`).
114
+
- Data url, base-64 encoded (`readAsDataURL`).
115
+
116
+
In many cases though, we don't have to read the file contents.
117
+
118
+
We can create a blob url with `URL.createObjectURL(file)` and assign it to `<a>` or `<img>`. This way the file can be downloaded or show up as an image, as a part of canvas etc.
119
+
120
+
And if we're going to send a `File` over a network, then it's also easy, as network API like `XMLHttpRequest` or `fetch` natively accepts `File` objects.
Copy file name to clipboardExpand all lines: 7-network/1-fetch-basics/article.md
+37-193
Original file line number
Diff line number
Diff line change
@@ -16,39 +16,17 @@ let promise = fetch(url, [params])
16
16
17
17
The browser starts the request right away and returns a `promise`.
18
18
19
-
Accepting a response is usually a two-step procedure.
19
+
Accepting a response is usually a two-stage process.
20
20
21
-
**The `promise` resolves as soon as the server responded with headers.**
21
+
**The `promise` resolves with an object of the built-in [Response](https://fetch.spec.whatwg.org/#response-class) class as soon as the server responds with headers.**
22
22
23
-
So we can access the headers, we know HTTP status, whether the response is successful, but don't have the body yet.
24
-
25
-
We need to wait for the response body additionally, like this:
26
-
27
-
```js run async
28
-
let response =awaitfetch('https://api.github.com/repos/iliakan/javascript-tutorial-en/commits');
console.log(`Received ${receivedLength} of ${contentLength}`)
192
-
}
193
-
194
-
// Step 4: join chunks into result
195
-
let chunksAll =newUint8Array(receivedLength); // (4.1)
196
-
let position =0;
197
-
for(let chunk of chunks) {
198
-
chunksAll.set(chunk, position); // (4.2)
199
-
position +=chunk.length;
200
-
}
94
+
document.body.append(img);
201
95
202
-
// Step 5: decode
203
-
let result =newTextDecoder("utf-8").decode(chunksMerged);
204
-
let commits =JSON.parse(result);
96
+
// show it
97
+
img.src=URL.createObjectURL(blob);
205
98
206
-
// We're done!
207
-
alert(commits[0].author.login);
99
+
setTimeout(() => { // hide after two seconds
100
+
img.remove();
101
+
URL.revokeObjectURL(img.src);
102
+
}, 2000);
208
103
```
209
104
210
-
Let's explain that step-by-step:
211
-
212
-
1. We perform `fetch` as usual, but instead of calling `response.json()`, we obtain a stream reader `response.body.getReader()`.
213
-
214
-
Please note, we can't use both these methods to read the same response. Either use a reader or a response method to get the result.
215
-
2. Prior to reading, we can figure out the full response length by its `Content-Length` header.
216
-
217
-
It may be absent for cross-domain requests (as in the example) and, well, technically a server doesn't have to set it. But usually it's at place.
218
-
3. Now `await reader.read()` until it's done.
219
-
220
-
We gather the `chunks` in the array. That's important, because after the response is consumed, we won't be able to "re-read" it using `response.json()` or another way (you can try, there'll be an error).
221
-
4. At the end, we have `chunks` -- an array of `Uint8Array` byte chunks. We need to join them into a single result. Unfortunately, there's no single method that concatenates those.
222
-
1. We create `new Uint8Array(receivedLength)` -- a same-type array with the combined length.
223
-
2. Then use `.set(chunk, position)` method that copies each `chunk` at the given `position` (one by one) in the resulting array.
224
-
5. We have the result in `chunksAll`. It's a byte array though, not a string.
225
-
226
-
To create a string, we need to interpret these bytes. The built-in `TextEncoder` does exactly that. Then we can `JSON.parse` it.
227
-
228
-
What if it were a binary file? We could make a blob of it:
229
-
```js
230
-
let blob =newBlob([chunksAll.buffer]);
231
-
```
232
-
233
-
```js run async
234
-
let response = await fetch('https://api.github.com/repos/iliakan/javascript-tutorial-en/commits?per_page=100');
0 commit comments