JS实战题大赏

355 阅读1分钟

1. 【MOKA】实现add方法,可以相加多个数据并返回结果

// 通过调用下面的addRemote,实现add方法
// addRemote仅能计算两个数字之和
// add可以传入任意多个数字,返回的是这些数字之和
const addRemote = async (a, b) =>
  new Promise((resolve) => {
    setTimeout(() => resolve(a + b), 1000);
  });

// 这是你需要实现的方法add
async function add(...inputs) {
}

// 请用示例验证运行结果:
add(1, 2).then((result) => {
  console.log(result); //3
});
add(3, 5, 2).then((result) => {
  console.log(result); //10
});
// 实现方法
async function add(...inputs) {
    // 1. 定义变量结果
    let res = 0
    // 2. 遍历循环
    for(let i = 0; i < inputs.length; i ++) {
        // 3. 等待返回结果,重新赋值res
        res = await addRemote(res, inputs[i])
    }
    // 4. 返回Prmose的resolve实例
    return Promise.resolve(res)
 }

2. 【高途】异步执行任务

new Promise(resolve => {
  console.info(1)
  setTimeout(resolve, 100, 2)
  console.log(3)
}).then((data) => {
  console.info(data)
})

// 打印结果 1 3 2
/*
  setTimeout(fn, time, args)
    - fn 回调函数
    - time 等待时间
    - args fn的参数
*/

2. 【美团、知乎】高阶版异步执行任务

console.info('start')
async function async1() {
    await async2()
    console.log('async1')
}
async function async2() {
    console.log('async2')
}
setTimeout(function() {
  console.log(1)
}, 0)
new Promise(function(resolve) {
  console.log(2)
  forvar i=0 ; i<10000 ; i++ ) {
    i == 9999 && resolve()
  }
  console.log(3)
}).then(function() {
  console.log(4)
}).then(function () {
  console.log(5)
})
Promise.resolve().then(function () {
  console.log(6)
})
async1()
console.info('end')
// start 2 3 async2 end 4 6 async1 5 1

/*
  主要考查异步任务执行顺序。从上到下先执行同步任务,再执行异步微任务,再执行异步宏任务
  先同后promise / async,再执行 setTimeOut
  - Promise的then方法是异步的,执行then链时,会放到微任务的异步执行队列中
*/

3. 【字节】接口加载异常时,实现间隔一定的时间,重复执行n次

// try catch 不能捕获异步的方法,需要做同步处理
// 使用async同步执行异步
async reloadFn(n, interval) {
    if(n === 0) return false // n为0不再执行
    n-- // 每次n减少执行1次
    try {
        let res = await Promise.reject('err') // 同步执行等待异步结果
        throw res // 抛异常
    } catch(error) {
        // 一定间隔内再次执行
        setTimeout(() => {
            reloadFn(n, interval)
        }, interval)
    }
}
reloadFn(4, 1000)
//  每隔1秒打印‘err’,打印4次