Skip to content

Commit 8e84437

Browse files
authored
Merge pull request devkodeio#31 from thevinayysharma/main
Added: questions on promise
2 parents a832c25 + 5c89b79 commit 8e84437

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

code-snippets/promises.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,5 +250,77 @@ new Promise((resolve, reject) => {
250250
</details>
251251
</li>
252252

253+
---
254+
255+
<li>
256+
257+
**What's the output of the following Promise Operation?**
258+
259+
```JS
260+
const promise_1 = Promise.resolve('First');
261+
const promise_2 = Promise.resolve('Second');
262+
const promise_3 = Promise.reject('Third');
263+
const promise_4 = Promise.resolve('Fourth');
264+
265+
const runPromises = async () => {
266+
const res1 = await Promise.all([promise_1, promise_2])
267+
const res2 = await Promise.all([promise_3, promise_4])
268+
return [res1, res2];
269+
}
270+
271+
runPromises()
272+
.then(res => console.log(res))
273+
.catch(err => console.log(err))
274+
```
275+
276+
- A: `[['First', 'Second'], ['Third']]`
277+
- B: `[['First', 'Second'], ['Third', 'Fourth']]`
278+
- C: `[['First', 'Second']]`
279+
- D: `'Third'`
280+
281+
<br/>
282+
<details>
283+
<summary><b>Answer</b></summary>
284+
<p>
285+
286+
#### Option: D
287+
288+
> `Promise.all[...promises]` method wait for an array of promises to resolve. Promise.all() will reject immediately upon any of the input promises being rejected. In our case, During runPromises() function invocation, promise_3 gets rejected with the value 'Third'. The value gets logged to the console, via error handling Promise Instance Method `catch()`. As a result, 'Third' gets printed.
289+
290+
</p>
291+
</details>
292+
</li>
293+
294+
---
295+
296+
<li>
297+
298+
**What's the output of the following Promise operation?**
299+
300+
```JS
301+
var p = new Promise((resolve, reject) => {
302+
reject(Error('The Fails!'))
303+
})
304+
p.catch(error => console.log(error.message))
305+
p.catch(error => console.log(error.message))
306+
```
307+
308+
- A: `print error message once`
309+
- B: `print error message twice`
310+
- C: `Unhandled Promise Rejection warning`
311+
- D: `process exits`
312+
313+
<br/>
314+
<details>
315+
<summary><b>Answer</b></summary>
316+
<p>
317+
318+
#### Option: B
319+
320+
> The promise `p` gets rejected due to `reject` callback in Promise Constructor and the error message gets attached to the `.catch()` method. In this case, `.catch()` works like the DOM `.addEventListener('event', callback`) method. Both catch method will be called separately with the same arguments. Hence, the error message gets printed twice.
321+
322+
</p>
323+
</details>
324+
</li>
253325

254326
</ol>

0 commit comments

Comments
 (0)