解题之前建议大家先看看promise的文档[https://segmentfault.com/a/1190000002452115]
第一题:promise应用的面试题
红灯三秒亮一次,绿灯一秒亮一次,黄灯2秒亮一次;如何让三个灯按照这个规律不断交替重复亮灯?(用Promse实现)三个亮灯函数已经存在:
function red(){
console.log('red');
}
function green(){
console.log('green');
}
function yellow(){
console.log('yellow');
}*
//已知函数
function red(){
console.log('red');
}
function green(){
console.log('green');
}
function yellow(){
console.log('yellow');
}*
//亮灯一次 函数
var lightUp = function(timmer, cl){
return new Promise(function(resolve, reject) {
setTimeout(function() {
cl();
resolve();
}, timmer);
});
};
//promise
var myPromise = new Promise(function(resolve, reject){resolve();});
var step = function(pro) {
pro.then(function(){
return lightUp(3000, red);
}).then(function(){
return lightUp(1000, green);
}).then(function(){
return lightUp(2000, yellow);
}).then(function(){
//递归
step(pro);
});
}
step(myPromise);
第二题:
实现一个LazyMan,可以按照以下方式调用:
LazyMan(“Hank”)输出:
Hi! This is Hank!
LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~
LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
Hi This is Hank!
Eat dinner~
Eat supper~
LazyMan(“Hank”).sleepFirst(5).eat(“supper”)输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
以此类推。
//等待函数
function wait(second) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Wake up after ' + second);
}, second * 1000);
});
}
//链式+promise
var LazyMan = function(name) {
var p = new Promise(function (resolve, reject) {
resolve('Hi! This is ' + name + '!');
});
return {
sleep: function (second) {
p = p.then(function (msg) {
console.log(msg);
return wait(second);
});
return this;
},
sleepFirst: function (second) {
var op = p;
p = wait(second).then(function (msg) {
console.log(msg);
return op;
});
return this;
},
eat: function (part) {
var pn = new Promise(function (resolve) {
resolve('Eat ' + part + '~');
});
p = p.then(function (msg) {
console.log(msg);
return pn;
});
return this;
},
print: function () {
return p.then(function (msg) {
console.log(msg);
});
}
};
}
exports.LazyMan = LazyMan;
本题有多种方案,感兴趣的可以尝试面向对象等其他方式来实现。