Importing / Exporting Only After Certain Promises Have Resolved
Solution 1:
You can't directly export the results of something retrieved asynchronously because export is synchronous, so it happens before any async results have been retrieved. The usual solution here is to export a method that returns a promise. The caller can then call that method and use that promise to get the desired async result.
module.exports = function() {
returnstep1().then(step2).then(step3).then(function() {
// based on results of above three operations, // return the filename herereturn ...;
});
}
The caller then does this:
require('yourmodule')().then(function(filename) {
// use filename here
});
One thing to keep is mind is that if any operation in a sequence of things is asynchronous, then the whole operation becomes asynchronous and no caller can then fetch the result synchronously. Some people refer to asynchronous as "contagious" in this way. So, if any part of your operation is asynchronous, then you must create an asynchronous interface for the eventual result.
You can also cache the promise so it is only ever run once per app:
module.exports = step1().then(step2).then(step3).then(function() {
// based on results of above three operations, // return the filename herereturn ...;
});
The caller then does this:
require('yourmodule').then(function(filename) {
// use filename here
});
Post a Comment for "Importing / Exporting Only After Certain Promises Have Resolved"