-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise&fetch.js
57 lines (47 loc) · 1.62 KB
/
promise&fetch.js
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
// a promise on declaration takes two callbacks resolve and reject
// a promise object has 2 properties -
// state = (resolved or rejected)
// result = (value or Error)
let promise = new Promise(function (resolve, reject){
console.log('loading...')
setTimeout(() => resolve('done'),2000)
});
// state & result are private and can only be accessed by
// - then(resultHandlingCallback, errorHandlingCallback) -> (to handle result error or both)
// - catch(errorHandlingCallback) -> (to handle error)
// - finally() -> (to pass error/result to next handler)
promise.then(
function (result){
console.log(result);
},
function (error){
console.log(error)
}
)
let newProm = new Promise((resolve,reject) => {
setTimeout(() => reject(new Error("Error")), 5000)
})
.finally(()=> console.log("promise ready..."))
.catch(error => console.log(error))
.then((result, error)=>{
console.table([
["inPromise","After Promise","time difference","setTimeout"],
["loading...", "done", "2", "2"],
["loading...", "promise ready...", "3", "5"]
])
})
.finally(() => console.log("coz both timers start at almost same time coz async"));
;
// ---------------------------------------------------------------------------
async function showAvater(){
let response = await fetch('https://api.github.com/users/rmarzooqur/following')
avatars = await response.json()
for (avatar of avatars){
let image = document.createElement('img')
image.src = avatar.avatar_url
document.body.append(image)
}
return avatar
}
showAvater() // returns a promise and await is alternative to .then
// ----------------------------------------------------------------------------