Ricerca…


Uso asincrono

Il pacchetto async fornisce funzioni per il codice asincrono.

Utilizzando la funzione automatica è possibile definire relazioni asincrone tra due o più funzioni:

var async = require('async');

async.auto({
    get_data: function(callback) {
        console.log('in get_data');
        // async code to get some data
        callback(null, 'data', 'converted to array');
    },
    make_folder: function(callback) {
        console.log('in make_folder');
        // async code to create a directory to store a file in
        // this is run at the same time as getting the data
        callback(null, 'folder');
    },
    write_file: ['get_data', 'make_folder', function(results, callback) {
        console.log('in write_file', JSON.stringify(results));
        // once there is some data and the directory exists,
        // write the data to a file in the directory
        callback(null, 'filename');
    }],
    email_link: ['write_file', function(results, callback) {
        console.log('in email_link', JSON.stringify(results));
        // once the file is written let's email a link to it...
        // results.write_file contains the filename returned by write_file.
        callback(null, {'file':results.write_file, 'email':'[email protected]'});
    }]
}, function(err, results) {
    console.log('err = ', err);
    console.log('results = ', results);
});

Questo codice potrebbe essere stato creato in modo sincrono, semplicemente chiamando get_data , make_folder , write_file e email_link nell'ordine corretto. Async tiene traccia dei risultati per te e, se si verifica un errore (primo parametro di callback non uguale a null ), interrompe l'esecuzione delle altre funzioni.



Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow