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

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

问题描述

我有两个javascript函数

  function one(){
do something long ... like writing jpgfile在磁盘上
}

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



我这样调用它(在jQuery中)

  one(); 
two();

因为函数二需要函数一的链接文件,所以我需要确保执行完成。 ..所以获取函数两个在函数的回调函数一个应该是骗子..但是如何这样做?



注意:我做了一个警报')之间的两个函数,让函数一个完成,它工作正常...当警报被注释(删除)没有什么工作了!

解决方案

你只需要使用一个回调,如果你正在做一些异步,否则不管多长时间,下一个函数将不会运行,直到第一个完成。



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

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

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

one(two);

显然,如果你是做异步的,会告诉你什么时候完成(例如事件触发)。


I have two javascript functions

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

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

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 ?

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天全站免登陆