promise to achieve simple operation step

I started going to the front less than a year, remember to go to a company interview, had not yet come into contact with ES6, let alone use at work, just to stay in for the promise glance at a document. At that time I remember the interviewer is asking, js finish first thing to realize 1, then 2 things, the last thing 3. He was thought for a moment with a handwritten es5 event callback hell about this issue,

1
2
3
4
5
6
7
8
9
function () {
do something1
function step2() {
dong something2
function step3 (){
do something3
}
}
}

Then put a bit less mouth can also use the promise, the results look the interviewer requested handwriting, he said at the time cool
after use es6 now look back, in fact, a promise is not difficult to achieve, but more simple

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
the let State = . 1 ; 
function ( Resolve, Reject ) { Console .log ( 'the first step' ); IF (State == . 1 ) { Resolve ( 'the first step is executed successfully' ) } the else { Reject ( 'the first step failed ' ) } }








function Step2 ( Resolve, Reject ) { Console .log ( 'second step' ); IF (State == . 1 ) { Resolve ( 'second step executed successfully' ) } the else { Reject ( 'second step fails' ) }}








function Step3 ( Resolve, Reject ) { Console .log ( 'the third step' ); IF (State == . 1 ) { Resolve ( 'the third step is executed successfully' ) } the else { Reject ( 'the third step failed' ) }}








new Promise(step1).then(function(res){
console.log(res)
return new Promise(step2)
}).then(function(res) {
console.log(res)
return new Promise(step3)
}).then(function(res) {
console.log(res)
})

Original: Big Box  promise simple implementation of Step by Step


Guess you like

Origin www.cnblogs.com/wangziqiang123/p/11618463.html