提问人:Abhishek Satyavolu 提问时间:6/23/2023 最后编辑:InSyncAbhishek Satyavolu 更新时间:6/23/2023 访问量:92
编写一个回调函数,使用提供的具有随机超时的异步函数按顺序打印三个字符
Write a callback function to print three characters sequentially using a provided async function with random timeout
问:
在一次 JavaScript 面试中,有人问我以下问题。我无法回答。请帮忙!
const printString = (string, callback) => {
setTimeout(() => {
console.log(string);
callback();
}, Math.random() * 1000);
};
使用字符 'a'、'b' 和 'c' 调用函数 printString 三次,并编写一个回调函数,以便按顺序打印 a、b 和 c。随心所欲地使用回调函数。
任何帮助都不胜感激:)
答:
2赞
adiga
6/23/2023
#1
您可以将调用包装在 promise 中,并作为回调传递。当在 中执行时,promise 将得到解析,并将移动到循环中的下一项。printString
res
callback
setTimeout
const printString = (string, callback) => {
setTimeout(() => {
console.log(string);
callback();
}, Math.random() * 1000);
};
const inputs = ['a', 'b', 'c'];
(async () => {
for (const n of inputs) {
await new Promise(res => printString(n, res));
}
})()
0赞
brk
6/23/2023
#2
这个问题对我来说并不完全清楚,因为没有提到我们是否可以使用 promise。我假设我们可以使用它,所以我的解决方案是创建一个承诺,然后在解析中我们可以调用回调
function printVal(val) {
console.log(val)
}
const printString = async(string, callback) => {
return new Promise(resolve => setTimeout(() => {
resolve(callback(string));
}, Math.random() * 1000))
};
const caseFunc = async() => {
const items = ['a', 'b', 'c'];
for (item of items) {
const val = await printString(item, printVal);
}
}
caseFunc()
评论
0赞
InSync
6/23/2023
我认为不允许修改给定的功能。
2赞
YK1
6/23/2023
#3
没有必要使用 Promises,最简单的答案是将方法本身链接为回调。printString
const printString = (string, callback) => {
setTimeout(() => {
console.log(string);
callback();
}, Math.random() * 1000);
};
printString('a',
() => printString('b',
() => printString('c', () => undefined)));
由于这是一个面试问题,可能会转移你的思想,让你认为他们会被叫乱,但事实并非如此。Math.random()
评论
setTimeout
里面是问题的一部分吗?printString