javascript Javascript函数执行同步
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22184831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript function execution synchronization
提问by kosta
I have three javascript files 1.js, 2.js, 3.js
我有三个 javascript 文件 1.js, 2.js, 3.js
1.js
1.js
function getOne()
{
return "one";
}
2.js
2.js
function getTwo()
{
return "two";
}
3.js
3.js
getOne(function(resp1)
{
console.log(resp1)
getTwo(function(resp2)
{
console.log(resp2);
}
});
The function calls in 3.js are not executed at all. I load the js files in the order 1.js 2.js 3.js
3.js 中的函数调用根本不执行。我按照 1.js 2.js 3.js 的顺序加载 js 文件
COuld someone please help
有人可以帮忙吗
回答by Martin Jespersen
The reason it doesn't work, as already mentioned, is that your methods don't handle the callbacks you pass in as arguments.
如前所述,它不起作用的原因是您的方法不处理您作为参数传入的回调。
To make it work like you want you need to rewrite your methods to look like this:
为了让它像你想要的那样工作,你需要重写你的方法,如下所示:
function getOne(callback)
{
callback("one");
}
function getTwo(callback)
{
callback("two");
}
Since you question is about function execution synchronization however, you might wish to go down another path.
但是,由于您的问题是关于函数执行同步,因此您可能希望走另一条路。
What you are doing will work fine for a couple of functions, but when you get to the point where you wish to synchronize many functions you end up with the pyramid of doomwhere code marches to the right faster than it marches forward.
你正在做的对于几个函数来说会很好,但是当你到达想要同步许多函数的地步时,你最终会陷入厄运金字塔,其中代码向右行进的速度比向前行进的速度要快。
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
...continue ad nauseum
});
});
});
});
In that case you might want to look into futures and promises
在这种情况下,您可能需要查看期货和承诺
You can read more about promise patterns in javascript here:
您可以在此处阅读有关 javascript 中的承诺模式的更多信息:
回答by Mike Christensen
The code:
代码:
getOne(function(resp1)
{
console.log(resp1)
getTwo(function(resp2)
{
console.log(resp2);
}
}
);
Does in fact call getOne
, however it passes in an anonymous function as a parameter. getOne
doesn't actually takeany parameters (though passing one doesn't hurt, nor cause any errors), nor is that anonymous function actually executedanywhere.
实际上调用getOne
,但是它传入一个匿名函数作为参数。 getOne
实际上不带任何参数(尽管传递一个不会伤害,也不会导致任何错误),匿名函数也不会在任何地方实际执行。
I'm not sure exactly what you're trying to do, but I'd start by giving getOne
a parameter:
我不确定你到底想做什么,但我首先给出getOne
一个参数:
function getOne(fnFoo)
{
return "one";
}
You'd then be able to call the function you pass in:
然后您就可以调用您传入的函数:
function getOne(fnFoo)
{
fnFoo();
return "one";
}