Settings
Synchronous or asynchronous refers to the execution flow of a program. When an operation executes completely before passing the control to the next, the execution is synchronous . This is the standard method of code execution - in languages I know, and I imagine that in most languages I do not know.
When one or more operations are time-consuming, it may be worthwhile to execute them asynchronously, so that the rest of the code can be executed without waiting for them to stop. In this case, the code following the command that triggers the asynchronous operation can not count on the result of this operation, of course. Everything that depends on the result of the operation needs to be done only when it has been completed, and usually this occurs in a callback , that is, a block of code (usually a function or method) the asynchronous operation.
Languages can implement asynchronism in different ways. This is usually done with Threads and Event Loops, like as in JavaScript .
Examples
In JavaScript, in the browser, the classic case of asynchronous operation is AJAX - for asynchronous JavaScript and XML. We call AJAX requests made to a server from JS on a web page. For example, with jQuery for abbreviation:
$.get('http://example.com', funcaoQueExecutaQuandoRespostaChegar);
// o código seguinte executa antes da resposta da requisição acima
fazAlgumaCoisa();
// e a declaração do callback
function funcaoQueExecutaQuandoRespostaChegar(resposta) {
// a resposta não pode ser usada fora daqui,
// a menos que você a passe, a partir daqui,
// para uma outra função
}
As the request is potentially time-consuming (and certainly more time-consuming than any local operation), if the request is synchronous the page will be frozen until the response arrives. Therefore it is recommended to use AJAX and callbacks in these cases.
Another typical example occurs in the desktop application user interface. If the program wants to show a progress bar indicating the progress of a time-consuming operation, it must necessarily use asynchronism. Otherwise the interface can only update the progress bar once, at the end of the operation - which would not make any sense to a progress bar!