阿里前端测试题--关于ES6中Promise函数的理解与应用

今天做了阿里前端的笔试题目,原题目是这样的

 1 //实现mergePromise函数,把传进去的数组顺序先后执行,
 2 //并且把返回的数据先后放到数组data中
 3 
 4 const timeout = ms => new Promise((resolve, reject) => {
 5 setTimeout(() => {
 6 resolve();
 7 }, ms);
 8 });
 9 
10 const ajax1 = () => timeout(2000).then(() => {
11 console.log('1');
12 return 1;
13 });
14 
15 const ajax2 = () => timeout(1000).then(() => {
16 console.log('2');
17 return 2;
18 });
19 
20 const ajax3 = () => timeout(2000).then(() => {
21 console.log('3');
22 return 3;
23 });
24 
25 const mergePromise = ajaxArray => {
26 // 在这里实现你的代码
27 
28 };
29 
30 mergePromise([ajax1, ajax2, ajax3]).then(data => {
31 console.log('done');
32 console.log(data); // data 为 [1, 2, 3]
33 });
34 
35 // 分别输出
36 // 1
37 // 2
38 // 3
39 // done
40 // [1, 2, 3]

 

 

从网上找到的答案我写贴上:

var data = [];
var sequence = Promise.resolve();
ajaxArray.forEach(function(item){
  sequence = sequence.then(item).then(function(res){
    data.push(res);
    return data;
  });
})

return sequence;

 

解答思路和原理有空再研究贴上来。

更新--思路解析:

  settimeout模拟异步函数执行:

func A(){

  setTimeout(function(){

    console.log('a');

},3000);

}

func B(){

  setTimeout(function(){

    console.log('b');

},1000);

}

A();

B();

那么你觉得输出结果是啥?不妨试下,会输出b,a.

当执行到A函数时,会注册一个三秒后执行的函数,直接去执行B,而不是等三秒执行完A再去执行B。

promise可以实现同步执行

先说一下使用方法吧:promise和then配合使用,类似于回调函数,执行完promise之后才会执行then的内容

new Promise((resolve, reject) {

}).then(function(){

}).then(function(){})...

promise里面的两个参数表示promise的执行状态

但是值得注意的是then里面的东西可不是同步执行,并不是前一个执行完再执行后一个,then之间还是遵循异步原则的。

所以JavaScript、nodejs想要实现同步,各路神仙都有自己不同的理解和套路。

后续更新。

posted @ 2018-07-22 20:59  阿明先森  阅读(2204)  评论(0编辑  收藏  举报