如何在javascript中向函数添加回调 [英] How to add a callback to a function in javascript

查看:33
本文介绍了如何在javascript中向函数添加回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 javascript 函数

I have two javascript functions

function one () {
   do something long... like writing jpgfile on disk
}

function two () {
   do something fast... like show the file
}

我这样称呼它(在 jQuery 中)

I call it (in jQuery) like this

 one ();
 two ();

因为函数二需要函数一的链接文件,我需要确保执行完成......所以在函数一的回调中获取函数二应该是诀窍......但是如何做到这一点?

Because function two needs the link file from function one, i need to be sure the execution is completed... so getting the function two in the callback of function one should be the trick.. but how to do that ?

注意:我确实在这两个函数之间放置了一个警报 ('aaa') 来让一个函数完成,它运行良好......当警报被注释(删除)时,没有任何作用!

note : I did put an alert ('aaa') between those two functions to let function one complete, and it worked fine... when the alert is commented (removed) nothing works anymore !

推荐答案

如果你在做一些异步的事情,你只需要使用回调,否则不管事情需要多长时间,下一个函数直到第一个已经完成.

You only need to use a callback if you are doing something asynchronous, otherwise it doesn't matter how long something takes, the next function won't run until the first has finished.

回调只是传递一个函数作为参数,然后在完成后调用它.

A callback is just passing a function as an argument, and then calling it when done.

function one (callback) {
   do something long... like writing jpgfile on disk
   callback();
}

function two () {
   do something fast... like show the file
}

one(two);

显然,如果你在做一些异步的事情,那么你需要一些东西来告诉你它什么时候完成(比如一个事件触发).

Obviously, if you are doing something asynchronous, then you need something that will tell you when it is finished (such as an event firing).

这篇关于如何在javascript中向函数添加回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆