-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPromiseMethod.js
More file actions
82 lines (61 loc) · 1.6 KB
/
PromiseMethod.js
File metadata and controls
82 lines (61 loc) · 1.6 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// const p1=new Promise(function (resolve,rejected){
// setTimeout(resolve,500,"Hii")
// })
// const p2=new Promise(function (resolve, reject){
// setTimeout(reject,133,"Error")
// })
// const p3=new Promise(function (resolve, reject){
// setTimeout(resolve,132,"Promise executed")
// })
// Promise.race([p1,p2,p3]).then((data)=>{
// console.log(data)
// })
// .catch(()=>{
// console.log("ERROR")
// })
// Promise.any([p1,p2,p3]).then((data)=>{
// console.log(data)
// }) // which iteration is first it is executed.
const urls = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2',
'https://jsonplaceholder.typicode.com/posts/3'
];
// function fetchData(url) {
// return fetch(url)
// .then((data)=>data.json())
// }
// async function fetchApi(url){
// const promise=url.map((link)=>fetchData(link)) // Array of promise
// try{
// const [first, ...rest] = await Promise.all(promise)
// console.log(first); //rest
// console.log("rest:",rest);
// }
// catch(err){
// console.log("Error: ",err);
// }
// }
// fetchApi(urls)
//using For-Each loop
function FetchData(url) {
return fetch(url)
.then((data)=>data.json())
.catch((err)=>{
console.log(err);
})
}
async function fetchApi(urls){
promise=[]
urls.forEach(element =>{
promise.push(FetchData(element))
});
try{
const result=await Promise.all(promise)
console.log(result);
}
catch(err){
console.log("Error: ",err);
}
}
fetchApi(urls)