外包面试题
- 代码运行后会输出什么结果?请写出来
- 如果希望每隔1s输出一个结果,应该怎么改?请修改里面的代码
const list = [1, 2, 3];
const square = num => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num * num);
}, 1000);
});
}
function test() {
// 修改这里的代码
list.forEach(async x => {
const res = await square(x);
console.log(res);
});
}
test()
</script>
1 .答案:1,4,9
2.修改
const list = [1, 2, 3]
const square = num => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (isNaN(num)) {
reject(new TypeError(`${num} 不是个数`))
} else {
resolve(num * num)
}
}, 1000)
})
}
// 串行
async function test() {
for (let i = 0; i < list.length; i++) {
let x = list[i]
const res = await square(x)
console.log(res)
}
}
test()
</script>