Javascript 在上一个函数完成后调用一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5000415/
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
Call a function after previous function is complete
提问by Rrryyyaaannn
I have the following JavaScript code:
我有以下 JavaScript 代码:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});
How can I ensure that function2
is called only after function1
has completed?
如何确保function2
仅在function1
完成后才调用?
回答by Mike Robinson
Specify an anonymous callback, and make function1 accept it:
指定一个匿名回调,并让 function1 接受它:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
...do stuff
callback();
}
回答by philwinkle
If you're using jQuery 1.5 you can use the new Deferreds pattern:
如果您使用的是 jQuery 1.5,则可以使用新的 Deferreds 模式:
$('a.button').click(function(){
if(condition == 'true'){
$.when(function1()).then(function2());
}
else {
doThis(someVariable);
}
});
Edit: Updated blog link:
编辑:更新博客链接:
Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/
丽贝卡墨菲在这里写了一篇很棒的文章:http: //rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/
回答by TuanTruong
Try this :
尝试这个 :
function method1(){
// some code
}
function method2(){
// some code
}
$.ajax({
url:method1(),
success:function(){
method2();
}
})
回答by Domysee
This answer uses promises
, a JavaScript feature of the ECMAScript 6
standard. If your target platform does not support promises
, polyfill it with PromiseJs.
这个答案使用标准promises
的 JavaScript 特性ECMAScript 6
。如果您的目标平台不支持promises
,请使用PromiseJs对其进行polyfill。
Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:
Promise 是在 JavaScript 中处理异步操作的一种新的(而且更好)方式:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable).then(function() {
//this function is executed after function1
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
return new Promise(function (fulfill, reject){
//do stuff
fulfill(result); //if the action succeeded
reject(error); //if the action did not succeed
});
}
This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then
statements:
对于这个简单的例子来说,这似乎是一个很大的开销,但对于更复杂的代码,它比使用回调要好得多。您可以使用多个then
语句轻松链接多个异步调用:
function1(someVariable).then(function() {
function2(someOtherVariable);
}).then(function() {
function3();
});
You can also wrap jQuery deferrds easily (which are returned from $.ajax
calls):
您还可以轻松包装 jQuery deferrds(从$.ajax
调用返回):
Promise.resolve($.ajax(...params...)).then(function(result) {
//whatever you want to do after the request
});
As @charlietfl noted, the jqXHR
object returned by $.ajax()
implements the Promise
interface. So it is not actually necessary to wrap it in a Promise
, it can be used directly:
正如@charlietfl 所指出的,jqXHR
返回的对象$.ajax()
实现了Promise
接口。所以其实没有必要把它包裹在 a 中Promise
,直接使用即可:
$.ajax(...params...).then(function(result) {
//whatever you want to do after the request
});
回答by de Raad
Or you can trigger a custom event when one function completes, then bind it to the document:
或者您可以在一个函数完成时触发自定义事件,然后将其绑定到文档:
function a() {
// first function code here
$(document).trigger('function_a_complete');
}
function b() {
// second function code here
}
$(document).bind('function_a_complete', b);
Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.
使用这种方法,函数 'b' 只能在函数 'a' 之后执行,因为触发器仅在函数 a 执行完毕后才存在。
回答by Russell
This depends on what function1 is doing.
这取决于 function1 在做什么。
If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.
如果 function1 正在执行一些简单的同步 javascript,例如更新 div 值或其他内容,则 function2 将在 function1 完成后触发。
If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:
如果 function1 正在进行异步调用,例如 AJAX 调用,您将需要创建一个“回调”方法(大多数 ajax API 都有一个回调函数参数)。然后在回调中调用 function2。例如:
function1()
{
new AjaxCall(ajaxOptions, MyCallback);
}
function MyCallback(result)
{
function2(result);
}
回答by Jay Momaya
you can do it like this
你可以这样做
$.when(funtion1()).then(function(){
funtion2();
})
回答by Sahadeb Patro
If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.
如果方法 1 必须在方法 2、3、4 之后执行。以下代码片段可以作为在 JavaScript 中使用 Deferred 对象的解决方案。
function method1(){
var dfd = new $.Deferred();
setTimeout(function(){
console.log("Inside Method - 1");
method2(dfd);
}, 5000);
return dfd.promise();
}
function method2(dfd){
setTimeout(function(){
console.log("Inside Method - 2");
method3(dfd);
}, 3000);
}
function method3(dfd){
setTimeout(function(){
console.log("Inside Method - 3");
dfd.resolve();
}, 3000);
}
function method4(){
console.log("Inside Method - 4");
}
var call = method1();
$.when(call).then(function(cb){
method4();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
回答by StashOfCode
If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :
如果 function1 是某个同步函数,您希望将其转换为异步函数,因为它需要一些时间才能完成,并且您无法控制它添加回调:
function function1 (someVariable) {
var date = Date.now ();
while (Date.now () - date < 2000); // function1 takes some time to complete
console.log (someVariable);
}
function function2 (someVariable) {
console.log (someVariable);
}
function onClick () {
window.setTimeout (() => { function1 ("This is function1"); }, 0);
window.setTimeout (() => { function2 ("This is function2"); }, 0);
console.log ("Click handled"); // To show that the function will return before both functions are executed
}
onClick ();
The output will be :
输出将是:
Click handled
...and after 2 seconds :
...并在 2 秒后:
This is function 1
This is function 2
This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.
这是有效的,因为调用 window.setTimeout() 会向 JS runtine 任务循环添加一个任务,这是异步调用所做的,并且因为 JS 运行时“运行到完成”的基本原则确保了 onClick()在它结束之前永远不会被打断。
Notice that this as funny as it may the code difficult to understand...
请注意,这很有趣,因为代码可能难以理解......