2017-01-21 7 views
0

私はES6の約束事を理解しようとしています。そこには1秒間、私はそれがあると思っていましたが、私はそうは思わないでしょう。なぜ、最初のものが最初のものの前に返されますか?

私はたくさんのファイルを作成して読みたいと思っていますが、この操作が完了した後で次の操作を行うために移動してください。私にとって、これはPromisesにうまく当てはまりますが、最初の操作が完了する前に2回目の操作が復帰している理由を混乱させています。

私は約束を返す関数ensureFileExistsを作成しました。これをコールバックとしてfileNames.mapに渡します。これはコンソールにtrueの配列を記録します。これは私が期待しているものです。しかし私の混乱は、私の最初のthenが完了した後に私の最初のthenが呼び出されると思った。

私の最初のthenの前に私の2番目のthenがなぜ戻ってくるのか誰でも詳しく説明できたら、私は感謝します。

getFileNames(ensureFileExists) { 
    for(let i = 0; i < this.fileCount; i++) { 
    this.fileNames.push(this.generateRandomfileNames()); 
    }; 
    Promise.all(this.fileNames.map((file) => ensureFileExists(file))) 
     .then(values => console.log(values)) 
     .then(console.log(1)) // Why is this logged before values??? 
     .catch(err => console.log(err)) 
}; 

ensureFileExists(file) { 
    return new Promise((resolve, reject) => { 
    let filePath = path.join(this.src, file); 

    fsExtra.ensureFile(filePath, (err) => { 
     if (err === 'undefined') { 
     reject(new Error('Error creating file')); 
     } else { 
     resolve(true); 
     } 
    }); 
    }) 
}; 

答えて

3

このライン:

.then(console.log(1)) 

はすぐconsole.logを呼び出し、そしてthenメソッドに戻り値を渡します。

あなたは、おそらくこのように、より多くのあなたの前のラインでコールバック関数のような何かをしたい:

.then(() => console.log(1)) 
0

理由はあなたがコールバック関数としてconsole.logを渡していないが、あなたはすぐにそれを実行していることです戻り値(undefined)をthen引数に渡します。

第2のthenでは、無名関数を渡しますが、実行していません。このよう

function myFunction() { 
    console.log("inside myFunction()"); 
} 

function then(fnCallback) { 
    console.log("inside then()"); 
    fnCallback(); 
} 


then(myFunction); 
    /* Log: 
     inside then() 
     inside myFunction() 
    */ 



then(() => myFunction()); 
    /* Log: 
     inside then() 
     inside myFunction() 
    */   



then(function() { myFunction() }); 
    /* Log: 
     inside then() 
     inside myFunction() 
    */   



/* what happens here: 
    1) executes myFunction(), that returns undefined 
    2) executes then() with undefined as argument 
    3) try to call fnCallback (which is undefined), and trows an error 
*/ 
then(myFunction()); 
    /* Log: 
     inside myFunction() 
     inside then() 
     Uncaught TypeError: fnCallback is not a function 
    */ 
関連する問題