我对基本应用程序的控制流程有一个简单的菜鸟问题。我有3个带有setTimeout的函数。
console.log("[+] Program start");
function first(){
setTimeout(function(){
console.log(1);
},3000);}
function second(){
setTimeout(function(){
console.log(2);
},2000);}
function third(){
setTimeout(function(){
console.log(3);
},1000);}
first();
second();
third();
console.log("done");
预期输出如下:
[+] Program start
done
3
2
1
我想控制流程,以便按以下顺序查看内容:
[+] Program start
1
2
3
done
所以我通过以下方式重写了程序:
console.log("[+] Program start");
function first(){
setTimeout(function(){
console.log(1);
second();
},3000);}
function second(){
setTimeout(function(){
console.log(2);
third();
},2000);}
function third(){
setTimeout(function(){
console.log(3);
call();
},1000);}
first();
function call(){console.log("done ");}
输出为:
[+] Program start
1
2
3
done
现在输出正常,我想问你,这种方法对吗?用这种正确的方式如何控制流程或如何在node.js中编写?否则我完全走错了路。您能否检查一下,并给我一些提示,建议等。非常感谢您的帮助。
如果您要管理操作顺序,则绝对不想使用setTimeout()
它来执行操作。setTimeout()
设计用于阻止线程执行直到完成,并且使用这种方式会使您的应用程序异常脆弱。
假设您只是尝试管理流程,请阅读Node.js的事件循环的工作原理。以这种方式编写的代码将如下所示(我在其中添加了一些setTimeout()
函数来模拟/说明长时间运行的函数):
console.log("[+] Program start")
var first = function(callback) {
setTimeout(function() {
console.log(1)
callback()
}, 1000)
}
var second = function(callback) {
setTimeout(function() {
console.log(2)
callback()
}, 1000)
}
var third = function(callback) {
setTimeout(function() {
console.log(3)
callback()
}, 1000)
}
first(function() {
second(function() {
third(function() {
console.log("done ")
})
})
})
话虽这么说,以这样的嵌套方式使用回调有一个固有的缺点:“回调地狱”。您可以考虑使用诸如async
瀑布之类的功能或Promise库来对您的函数进行模块化。
优点:您也可以在ES6中编写功能链更加简洁:
first(() => second(() => third(() =>
console.log("done ")
)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句