2016-07-11 62 views
3

比方說,我有一個包含某些承諾的文件,按順序執行時,準備輸入文件input.txt只有在某些承諾解決後才能導入/導出

// prepareInput.js 
 

 
var step1 = function() { 
 
    var promise = new Promise(function(resolve, reject) { 
 
     ... 
 
    }); 
 
    return promise; 
 
}; 
 
       
 
var step2 = function() { 
 
    var promise = new Promise(function(resolve, reject) { 
 
     ... 
 
    }); 
 
    return promise; 
 
}; 
 
       
 
var step3 = function() { 
 
    var promise = new Promise(function(resolve, reject) { 
 
     ... 
 
    }); 
 
    return promise; 
 
}; 
 

 
step1().then(step2).then(step3); 
 

 
exports.fileName = "input.txt";

如果我運行node prepareInput.js,行step1().then(step2).then(step3)被執行,並創建文件。

我該如何改變這種情況,以便其他文件試圖從此模塊檢索fileName時,step1().then(step2).then(step3);在fileName被暴露之前運行並完成?沿着線的東西:

// prepareInput.js 
 
... 
 

 
exports.fileName = 
 
    step1().then(step2).then(step3).then(function() { 
 
     return "input.txt"; 
 
    }); 
 

 

 
// main.js 
 
var prepareInput = require("./prepareInput"); 
 
var inputFileName = require(prepareInput.fileName); 
 
      

的Node.js這裏初學者;事先道歉,如果我的方法使得完全沒有意義... :)

+2

爲什麼不'要求(」 ./ prepareInput')。fileName.then(function(inputFileName){...})'? –

+1

我的意思是一旦你的代碼被異步效應「感染」,你無法擺脫它,所有使用代碼的東西都變成異步。 –

+0

什麼是'first()'..? – Redu

回答

3

不能直接出口的異步檢索東西的結果,因爲出口是同步的,所以它發生任何異步結果都已經被檢索之前。這裏通常的解決方案是導出返回承諾的方法。調用者然後可以調用該方法並使用該承諾獲得所需的異步結果。

module.exports = function() { 
    return step1().then(step2).then(step3).then(function() { 
     // based on results of above three operations, 
     // return the filename here 
     return ...; 
    }); 
} 

主叫然後做到這一點:

require('yourmodule')().then(function(filename) { 
    // use filename here 
}); 

一保持件事是頭腦的是,如果在一個事物的序列中的任何操作是異步的,那麼整個操作變得異步和無調用者可以同步獲取結果。有些人以這種方式稱異步爲「傳染性」。所以,如果你的操作的任何部分是異步的,則必須創建爲最終結果的異步接口。


您也可以緩存的承諾,所以只能通過以往每個應用程序運行一次:

module.exports = step1().then(step2).then(step3).then(function() { 
    // based on results of above three operations, 
    // return the filename here 
    return ...; 
}); 

主叫然後做到這一點:

require('yourmodule').then(function(filename) { 
    // use filename here 
}); 
+0

我的情況不幸屬於「如果在一系列事物中的任何操作是異步的」。我將不得不考慮異步接口或改變我的方法。儘管如此,感謝您的詳細解釋! – S200