处理异步的几种方法:

详情见
https://www.cnblogs.com/zuobaiquan01/p/8477322.html

四种方法是对比

方法一:使用回调函数

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
 /使用定时函数模拟异步请求:

function doSomething(callback){
setTimeout(function(){
console.log('执行结束');
let result = 4;
callback(result);
},100);
}

function callback(result){
console.log('接收到结果为:'+result);
}

doSomething(callback);
doSomething((result)=>{console.log('接收到结果为:'+result)});
```


// 方法二:promise对象

function doSomething(){
return new Promise(function(resolve){
setTimeout(function(){
console.log('执行结束');
let result = 6;
resolve(result);
},100);
});

}

doSomething().then(result=>{
console.log('接收到结果为:'+result);
});



// 方法三:generator函数


function doSomething(){
setTimeout(function(){
let result = 6;
it.next(result);
},100);
}

function *gener(){
var result = yield doSomething();
console.log(result);
}

let it = gener();
it.next();


// 方法四:async(ES7)
function doSomething(){
return new Promise(resolve=>{
setTimeout(function(){
let result = 6;
resolve(result);
},100);
});

}

async function action(){
let result = await doSomething();
console.log(result);
}
action();