-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync-promise_async_await.js
67 lines (55 loc) · 1.54 KB
/
async-promise_async_await.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
56
57
58
59
60
61
62
63
64
65
66
let isOK=true;
// myResolve and myReject are the callback functions
// you can treate the myPromise as a long running function (eg. process images),
// but you need to supply a callback functions (success, fail) after running those long running code
// Simply Speaking: It just like a function, but you need to supply the functions and tell what should do after those long running code
// .catch() must be implement as it need to provide the reject callback
let myPromise = new Promise(function(myResolve, myReject) {
// The producing code (this may take some time)
// long runnning code (eg. process images)
if (isOK) {
myResolve("OK");
} else {
myReject("Error");
}
});
// the following 4 give the same results //
// FIRST
myPromise.then(
function(value) {console.log(value);},
function(error) {console.log(error);}
);
// SECOND
myPromise.then(
x => console.log(x),
y => console.log(y)
)
// THIRD
// myPromise.then(myResolve function).catch(myReject function)
myPromise.then((value)=>{console.log(value)}).catch((err)=>{console.log(err)});
// FORTH
myAsyncFct = async ()=>{
try{
let x = await myPromise;
console.log(x);
}catch(err){
console.log(err);
}
}
myAsyncFct();
// RESULT (let isOK=false)
// Error
// Error
// Error
// Error
// RESULT (let isOK=true)
// OK
// OK
// OK
// OK
myPromise.then((value)=>{console.log("P1 " + value); return value}).then((value)=>(console.log("P2 "+ value))).catch((err)=>{console.log("P1 " + err)});
// RESULT (let isOK=true)
// P1 OK
// P2 OK
// RESULT (let isOK=false)
// P1 Error