簡體   English   中英

在JavaScript函數中使用done作為參數是什么意思?

[英]What is the meaning of using done as a parameter in a javascript function?

我正在學習Javascript,並且似乎把函數作為參數完成是一個很難理解的概念。 我想知道為什么它的行為如此(作為參數完成(我想是完成的過程信號),並且是否有一些不錯的書或在線資源可以進一步研究這個概念。 例如 ,我將跟隨一個教程及其使用done作為參數,問題是當我通過gulp(gulpfile.js)在節點上運行代碼時,使用done時該過程永遠不會停止,如果我選擇跳過代碼中的done則它運行平穩。解決問題,我知道問題是作為參數完成的(我已經對其進行了多次檢查)。

gulp.task('clean-styles', function(done) {
    var files = config.temp + '**/*.css';
    clean(files, done);
});


function clean(path, done) {
    log('Cleaning: ' + $.util.colors.blue(path));
    del(path, done).then(function(path) {
        console.log("path=",util.inspect(path,false,null))
        console.log('Deleted Files\/Folders:\n', path.join('\n'));
        console.log('Finishing clean')
    });
}
  • 節點版本:0.12.4
  • npm版本:2.10.1
  • gulp版本:3.9.0

非常感謝您的幫助,我們將不勝感激。 稱呼。

只能解釋這個概念。 您試圖達到的目標還不夠清楚。

done只是一個函數(也稱為回調)的非官方標准名稱,它通知調用函數(stacktrace中的父代)任務已完成。

回想一下,javascript是異步的,並且函數可以作為變量傳遞。

現在,想象一個函數startPrinting ,它必須調用printText1printText2printText3 ,然后輸出該過程已完成的消息。 我們有:

function startPrinting() {
    printText1();
    printText2();
    printText3();
    console.log("completed");
}
function printText1() {
    $.get('http://ps-web.cloudapp.net/proxy.php?url=http://pastebin.com/raw.php?i=3uPCavLN', function(response){
        console.log(response)
    });
}
function printText2() {
    $.get('http://ps-web.cloudapp.net/proxy.php?url=http://pastebin.com/raw.php?i=jZjqKgNN', function(response){
        console.log(response)
    });
}
function printText3() {
    $.get('http://ps-web.cloudapp.net/proxy.php?url=http://pastebin.com/raw.php?i=SreCbunb', function(response){
        console.log(response)
    });
}

在此,不能保證在執行completed所有三個功能后始終會打印completed 因為它們異步執行。

為了對此進行排序,javascript忍者將引入完成函數,以便startPrinting僅在所有三個函數均已執行時才打印completed 請注意如何將函數傳遞給下面的printText1 ... 2

function startPrinting() {
    /* START OF DONE ROUTINE */
    var count = 0;
    var printCompleted = function() {
        count+=1;

        if(count == 3)
            console.log("completed");
    }
    /* END */
    printText1(printCompleted);
    printText2(printCompleted);
    printText3(printCompleted);
}
function printText1(done) {
    $.get('http://ps-web.cloudapp.net/proxy.php?url=http://pastebin.com/raw.php?i=3uPCavLN', function(response){
        console.log(response)
        done();
    });
}
function printText2(done) {
    $.get('http://ps-web.cloudapp.net/proxy.php?url=http://pastebin.com/raw.php?i=jZjqKgNN', function(response){
        console.log(response)
        done();
    });
}
function printText3(done) {
    $.get('http://ps-web.cloudapp.net/proxy.php?url=http://pastebin.com/raw.php?i=SreCbunb', function(response){
        console.log(response)
        done();
    });
}

我希望您能夠應用此原理來更好地了解您的上下文。

函數是JavaScript中的一流對象。 您可以像傳遞其他任何值一樣傳遞它們。 一旦將它們作為參數傳遞給另一個函數,則可以使用參數名稱來調用它們(或調用另一個函數並將其作為參數傳遞給該函數,或者分配它們的屬性,或者將它們轉換為字符串,或者其他方式想和他們一起做)。

 function this_sets_the_body() { document.body.innerHTML = "Hello, world"; } function this_calls_a_callback(im_a_callback) { im_a_callback(); } this_calls_a_callback(this_sets_the_body); 

在代碼中,您已經使用匿名函數表達式編寫了一個函數:

 function(done) { // ... } 

…並且您已經告訴它期望以您稱為done的參數來調用它。

無論將什么值傳遞給它,您都將忽略(您的函數在參數名稱后沒有提及done )。

您正在使用的庫(大概)正在其中傳遞一個函數,並且希望您在函數完成后立即調用它。 這樣一來,它就可以等到您正在執行的所有異步操作完成為止。

因此,在代碼完成后調用done()

看來您的示例在回調方面完全搞砸了。 在您的示例中的某些地方, done被用作回調-從外部給定的函數,當異步過程中的所有操作完成並發出操作結束信號時,將調用該函數。 在其他情況下,它似乎用作執行方法本身提供的參數。 在另一種情況下,您可以在promise使用它。 無論如何,由於我對 gulp 並不熟悉,所以我只能猜測,但是我希望以下示例可以為您解釋callback和部分promise的概念。 但是,我建議避免在同一代碼中丟失回調和Promise的情況,因為這會導致混亂。

gulp.task('clean-styles', function(done) {
   console.log(1);
   /* we are in the callback of gulp.task: we give the
    * latter this anonymous function to call when the 
    * setup is ready and it gives us function done to
    * call when we are done and signal the engine any errors
    */
   var files = config.temp + '**/*.css';

   /* this defines the action to take when files are actually deleted */
   var callback = function(err, message) {
       console.log(6);
       console.log(message); // expect: looks good
       // this is provided apparently by gulp and calling it signals the engine that everything is completed
       done(err);
   };

   /* we call this function, but some bits (like deletion 
    * run asynchronously. The function will return quickly, but
    * callback (function) will only be called when files are deleted */
   clean(files, callback);
   /* the execution of gulp.task callback is finished,
    * but files are not yet deleted */
   console.log(4);
});

/* done here is not the same done as above, it is actually
 * the function we supply into the call above, i.e. `callback` */
function clean(path, done) {
    /* the cleanup is starting */
    console.log(2);
    /* del is scheduled. it returns a `promise` and if
     * we call `then`, then the given anonymous function
     * will be executed when files are deleted. This is
     * where we call the provided function `done` to
     * signal that the job is complete and execute some action */
    del(path).then(function() {
        /* files are deleted and this callback is called */
        console.log(5);
        /* we let the outer caller know by calling `done` which
         * was given to us from outside */
        done(null, "looks good"); // null means no error
    }).catch(function(err) {
        done(err, "looks bad"); // err is given back
    });
    /* the clean method is through, but files not yet deleted */
    console.log(3);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM