面试题:
function fn1(cb) {
setTimeout(() => {
console.log("fn1");
cb();
}, 3000);
}
function fn2(cb) {
setTimeout(() => {
console.log("fn2");
cb();
}, 1000);
}
function fn3(cb) {
setTimeout(() => {
console.log("fn3");
cb();
}, 2000);
}
euque([fn1, fn2, fn3])//输出fn1,fn2,fn3
function euque(list) {
//code
}
解答
function fn1(cb) {
setTimeout(() => {
console.log("fn1");
cb();
}, 3000);
}
function fn2(cb) {
setTimeout(() => {
console.log("fn2");
cb();
}, 1000);
}
function fn3(cb) {
setTimeout(() => {
console.log("fn3");
cb();
}, 2000);
}
euque([fn1, fn2, fn3])//输出fn1,fn2,fn3
function euque(list) {
(async()=>{
for(let i= 0;i<list.length;i++) {
await new Promise((res,rej)=>{
list[i](res)
})
}
})()
}
思考
此方法只可以用for 或者 while循环,其他的遍历方法不可以
拿forEach举例,其源码就是封装的while循环,所多一层。async await 起不到作用,
模拟forEach实现
let CustomForeach = async (arr, callback) => {
const length = arr.length;
const O = Object(arr);
let k = 0;
while (k < length) {
if (k in O) {
console.log('doing foreach...');
const kValue = O[k];
await callback(kValue, k, O);
}
k++;
}
};
function fn1(cb) {
setTimeout(() => {
console.log("fn1");
cb();
}, 3000);
}
function fn2(cb) {
setTimeout(() => {
console.log("fn2");
cb();
}, 1000);
}
function fn3(cb) {
setTimeout(() => {
console.log("fn3");
cb();
}, 2000);
}
euque([fn1, fn2, fn3])//输出fn1,fn2,fn3
function euque(list) {
(async()=>{
CustomForeach(list,async(item) => {
await new Promise((res,rej)=>{
item(res)
})
})
})()
}
fn1
doing foreach...
fn2
doing foreach...
fn3
网友评论