gpt4 book ai didi

javascript - 本例中如何使用回调函数?

转载 作者:行者123 更新时间:2023-11-28 16:57:13 25 4
gpt4 key购买 nike

大家晚上好!我的代码有一个小问题,无法正确解决。我需要通过回调函数向控制台输出最简单的汤配方。请各位帮忙指点一下。提前致谢!

从在线教程和 YouTube 中,我了解到,如果我们将一个函数作为参数传递给另一个函数,那么这是一个回调函数。

// Put the water to boil
function setWater(param){
console.log('We start to cook the soup. We put the water to warm.');
param();
}

// Chop the onion
function cutOnion(param){
setTimeout(() => {
console.log('Chop the onion');
param();
}, 5000);
}

// Chop the carrot
function cutCarrot(param){
setTimeout(() => {
console.log('Chop the carrot');
param();
}, 6000);
}

// We are waiting for the water to boil.
function waitForWater(param){
setTimeout(() => {
console.log('We are waiting for the water to boil.');
param();
}, 10000);
}

// Put the onion in the water
function putOnion(param){
setTimeout(() => {
console.log('Put the onion in the water');
param();
}, 12000);
}

// Put the carrot in the water
function putCarrot(param){
setTimeout(() => {
console.log('Put the carrot in the water');
param();
}, 14000);
}

// Soup Is Ready
function soupIsReady(){
setTimeout(() => {
console.log('Soup is ready');
}, 20000);
}

setWater(cutOnion);
cutOnion(cutCarrot);
cutCarrot(waitForWater);
waitForWater(putOnion);
putOnion(putCarrot);
putCarrot(soupIsReady)

我需要在计时器上依次执行这些函数。

最佳答案

您可以使用reduceRight将回调链累积到一个函数中,然后调用它。这样您就可以避免通常所说的“回调 hell ”:

[setWater, cutOnion, waitForWater, putOnion, putCarrot, soupIsReady].reduceRight((acc, f) => 
() => f(() => acc())
)();

function setWater(param){ console.log('We start to cook the soup. We put the water to warm.'); param();}
function cutOnion(param){ setTimeout(() => { console.log('Chop the onion'); param(); }, 500); }
function cutCarrot(param){ setTimeout(() => { console.log('Chop the carrot'); param(); }, 600); }
function waitForWater(param){ setTimeout(() => { console.log('We are waiting for the water to boil.'); param(); }, 1000); }
function putOnion(param){ setTimeout(() => { console.log('Put the onion in the water'); param(); }, 1200); }
function putCarrot(param){ setTimeout(() => { console.log('Put the carrot in the water'); param(); }, 1400); }
function soupIsReady(){ setTimeout(() => { console.log('Soup is ready'); }, 2000); }

为了演示的目的,我减少了所有延迟,因此这些步骤更快地相互衔接。

关于javascript - 本例中如何使用回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com