3 回答
TA贡献1784条经验 获得超9个赞
您可以使用reduceRight将回调链累积到一个函数中,然后调用它。通过这种方式,您可以避免通常所说的“回调地狱”:
[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); }
出于演示的目的,我减少了所有延迟,因此这些步骤会更快地相互跟进。
TA贡献1873条经验 获得超9个赞
function callback(){
setWater(function() {
cutOnion(function(){
cutCarrot(function(){
waitForWater(function(){
putOnion(function(){
putCarrot(function(){
soupIsReady();
});
});
});
});
});
});
}
TA贡献1805条经验 获得超10个赞
我看到这样的东西......
// Put the water to boil
function setWater(param) {
console.log('We start to cook the soup. We put the water to warm.');
fct = param.shift();
fct(param);
}
// Chop the onion
function cutOnion(param) {
setTimeout(() => {
console.log('Chop the onion');
fct = param.shift();
fct(param);
}, 1000);
}
// Chop the carrot
function cutCarrot(param) {
setTimeout(() => {
console.log('Chop the carrot');
fct = param.shift();
fct(param);
}, 1000);
}
// We are waiting for the water to boil.
function waitForWater(param) {
setTimeout(() => {
console.log('We are waiting for the water to boil.');
fct = param.shift();
fct(param);
}, 1000);
}
// Put the onion in the water
function putOnion(param) {
setTimeout(() => {
console.log('Put the onion in the water');
fct = param.shift();
fct(param);
}, 1000);
}
// Put the carrot in the water
function putCarrot(param) {
setTimeout(() => {
console.log('Put the carrot in the water');
fct = param.shift();
fct(param);
}, 1000);
}
// Soup Is Ready
function soupIsReady() {
setTimeout(() => {
console.log('Soup is ready');
}, 1000);
}
setWater([cutOnion, cutCarrot, waitForWater, putOnion, putCarrot, soupIsReady]);
.as-console-wrapper {min-height:100% !important; top:0;}
添加回答
举报