jquery同步函数
有没有办法在另一个函数完成后运行一个函数?例如:
doSomething();
doSomethingElse();
我只想在 doSomething 完成后运行 doSomethingElse() 。这可能吗?
Is there a way to run a function after another functions completes? For example:
doSomething();
doSomethingElse();
i only want doSomethingElse() to run after doSomething completes. is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您的
doSomething()
函数正在异步执行某些操作(例如发出 Ajax 请求),那么您需要让doSomethingElse()
作为该异步请求的回调,而不是而不是在doSomething()
返回后立即执行。If your
doSomething()
function is doing something asynchronously (such as making an Ajax request) then you'll want to makedoSomethingElse()
the callback for that asynchronous request, rather than having it execute immediately afterdoSomething()
returns.实际上你可以用 jQuery 做你想做的事(至少在某种意义上)。它可能被认为有点hacky但工作完美。
只需在页面中包含一个不用于其他用途的元素即可。例如某处的空 div 。
然后将 JS 包含在您的函数中 + 我编写的
runMe
函数。这将生成三个警报,它们之间的距离为 1 秒,分别为“First”、“Second”、“Third”。
如果您不想延迟,请删除 setTimeout 并将调用留给
$(selec).dequeue("syncFnQueue");
。如果您的函数需要参数,例如
doSomething(x,y,z)
,您需要将runMe
函数调整为更好的部分,并以不同的方式构造返回的函数。检查此处或发布新问题。javascript 部分
Actually you can do what you want with jQuery (at least in some sense). It could be considered a little bit hacky but works flawless.
Just include an element in your page which you don't use for anything else. e.g. an empty div somewhere.
And then include the JS with your functions + the
runMe
function written by me.This would generate three alerts with a distance of 1s between them saying "First", "Second", "Third".
If you want no delay remove the setTimeout and just leave the call to
$(selec).dequeue("syncFnQueue");
.If your functions need parameters e.g.
doSomething(x,y,z)
you need to adapt therunMe
function to be a better partial and to construct the returned function differently. Check here or post new question.javascript partial
你可能想这样做......
You may want to do this....
问题有点模糊。
如果您的函数具有异步位,请使用回调。这就是他们的目的。
但是,如果您想在 JavaScript 中进行面向方面的编程,请查看 jQuery- aop。
The question is a bit vague.
If your functions have asynchronous bits to them, then use callbacks. That's what they are for.
If, however, you want to do aspect-oriented programming in JavaScript, take a look at jQuery-aop.
本身没有办法明确强制执行此操作,但一个想法是让 doSomething() 返回一个 doSomethingElse() 接受作为参数的值:
这样至少可以防止有人在不提供参数的情况下调用 doSomethingElse()需要......当然,他们是否通过调用 doSomething() 获得该参数是另一个问题。但这是一个开始。
想法源自 Code Complete。
There's no way to enforce this explicitly per se, but one idea is to have doSomething() return a value that doSomethingElse() accepts as a parameter:
that way at least you prevent somebody from calling doSomethingElse() without at least supplying the argument it needs... of course, whether they get that argument from calling doSomething() is another issue. But this is a start.
Idea lifted from Code Complete.