English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node.js callback function:L'asincronia è uno dei fattori fondamentali che hanno reso Node.js popolare. La callback è l'implementazione asincrona di una funzione. Di solito, nella Node.js, la maggior parte delle funzioni che gestiscono risorse hanno una variante di callback.
Quando si chiama una funzione asincrona per un task su una risorsa, il controllo viene immediatamente passato alla successiva istruzione della funzione. Il task sulla risorsa viene avviato in parallelo. Questo può aiutare Node.js continua ad eseguire altre attività mentre la funzione utilizza la risorsa. Una volta completato il task che utilizza la risorsa, Node.js utilizzerà la funzione di callback per riprendere. Chiamata The callback function has parameters: data object, result object, and/or an error object containing information related to the task.
Blocking function:In contrast to asynchronous functions, synchronous functions will execute a block until the resource is completed, so synchronous functions are also called blocking functions.
Node.js nested callback function : If multiple operations are performed on the resource sequentially and must be performed asynchronously, the callback functions can be nested.
Now, when reading (task) file (resource), we will see three cases compared to the callback function and blocking function.
Node.js blocking function example
Node.js callback function example
Esempio di funzione di callback annidata Node.js
Here is an example Node.js script that synchronously reads the sample.txt file.
var fs = require('fs'); // Read the file sample.txt var data = fs.readFileSync('sample.txt'); console.log("Reading file completed: " + new Date().toISOString()); console.log("After readFileSync statement: " + new Date().toISOString());
Quando viene eseguito il seguente programma
Output del terminale
arjun@arjun-VPCEH26EN:~/nodejs$ node read-file-sync.js Reading file completed: 2017-10-19T12:21:40.103Z After readFileSync statement: 2017-10-19T12:21:40.105Z
The after readFileSync statement always executes after the file reading is completed. fs.readFileSync blocks the execution flow.
Here is an example Node.js script, which usesNode.js callback functionAsynchronously read the sample.txt file.
var fs = require('fs'); // Read the file sample.txt fs.readFile('sample.txt', // Callback function called when reading the file is completed function(err, data) { if (err) throw err; // The data is a buffer containing the file content console.log("Reading file completed: " + new Date().toISOString()); }); console.log("After readFileSync asynchronously: " + new Date().toISOString());
Quando viene eseguito il seguente programma
Output del terminale
arjun@arjun-VPCEH26EN:~/nodejs$ node read-file-async.js Dopo la lettura asincrona: 2017-10-19T12:25:36.982Z Lettura del file completata: 2017-10-19T12:25:36.987Z
Potresti notare che, anche se esegui console.log dopo l'istruzione asincrona readFile, la lettura del file richiede circa 5 millisecondi. fs.readFile('sample.txt', callback function{..}) non blocca l'esecuzione, ma avvia in parallelo un nuovo processo con il flusso di controllo principale per leggere il file (eseguire compiti sulle risorse).
Per dimostrare le funzioni di callback annidate di Node.js, considereremo il piano di rinominare il file e poi eliminarlo utilizzando una funzione asincrona.
var fs = require('fs'); fs.rename('sample.txt', 'sample_old.txt', // Prima funzione di callback function (err) { if (err) throw err; console.log('File rinominato.'); fs.unlink('sample_old.txt', // Seconda funzione di callback function (err) { if (err) throw err; console.log('File cancellato.'); } ); } );
Quando il seguente esempio Node.js viene eseguito insieme a node
Output del terminale
arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-nested-callback.js File rinominato. File cancellato.
In questo tutorial Node.js – Funzioni di callback Node.js, abbiamo studiato il flusso di esecuzione delle funzioni di callback e come queste implementano la non-bloccante, nonché come combinare le funzioni di callback annidate con esempi.