-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path5-reject.js
More file actions
39 lines (34 loc) · 957 Bytes
/
5-reject.js
File metadata and controls
39 lines (34 loc) · 957 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'use strict';
// Task: support rejection with an error, if no more items in
// `items` array are available to return with `.next()`
// Change throwing error to returning rejected Promise.
// Catch error with `.catch` or `try/catch` to handle it.
const iterate = (items) => {
let index = 0;
return {
next: () =>
new Promise((fulfill) => {
if (index < items.length) {
return fulfill(items[index++]);
}
throw new Error('No more items to iterate');
}),
};
};
const electronics = [
{ name: 'Laptop', price: 1500 },
{ name: 'Keyboard', price: 100 },
{ name: 'HDMI cable', price: 10 },
];
const main = async () => {
const items = iterate(electronics);
const item1 = await items.next();
console.log(item1);
const item2 = await items.next();
console.log(item2);
const item3 = await items.next();
console.log(item3);
const item4 = await items.next();
console.log(item4);
};
main();