(今天给大家分享一道面试题)
面试题:
考察同步化执行的解决方案:
fun([
()=>console.log( 'start '),
()=>sleep(1000),
()=>console.log('1'),
()=>sleep( 2000),
()=>console.log( '2 '),
()=>sleep(3000),
()=>console.log( 'end ')
])
实现 sleep 等待对应的毫秒数后,再执行下面的方法。
实现方法1:(async-await 结合for循环)
sleep方法,返回一个promise对象
function sleep (ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
})
}
写一个方法,执行数组中的函数
async function fun (arr) {
for (let i:=0; i <: arr.length; i++){
await arr[i]();
}
}
实现方法2:(async-await 结合forEach 循环)
sleep方法和方法1一样,
主要是fun 中的实现不同,将for 改为forEach,
代码如下:
arr.forEach(async(fn)=> {
await fn();
})
你会发现,将for改成forEach后不能实现想要的效果
why?
why?
why?
原因是:
async -await 的同步化,只针对在同一个函数;
如以下代码:
test 与 test2是异步的,而f1,f2,f3 实现了同步化
async function test(){
await f1();
await f2();
await f3();
}
async function test2(){
}
改写forEach方法, 实现它的同步化
Array.prototype.myForEach = async function (callback,thisArg){
const _arr = this,
_isArray = Array.isArray(_arr),
_thisArg = thisArg ? 0bject(thisArg): window;
if ( !_isArray){
throw new TypeError('The caller of myForEach must be the type');
}
for (let i = 0; i <_arr.length; i ++){
await callback.call(_thisArg,_arr[i], i,_arr);
}
}
代码参考:
https://www.bilibili.com/video/BV1BR4y1x7ob?spm_id_from=333.999.0.0