idleberg idleberg - 19 days ago 7
Node.js Question

Return value from async function from its parent

I'm working on a build provider for the Atom text editor, which is a component based on the

package. This package allows you to run some tests to check whether a provider is eligible to run or not, returning
true
or
false
respectively.

I'm using
glob
to check whether a certain file-type is present in the project folder to determine whether to activate the build provider. For example, a project folder should include a LESS file in order to activate a build provider for
lessc
.

Example:

isEligible() {
const paths = glob.sync("**/*.less");

if (paths.length > 0) {
// one or more LESS files found
return true;
}

// no LESS files found
return false;
}


I'm wondering if the same is possible using
glob
asynchronously, specifically how I can return the state from
isEligible()
. The following does not work:

isEligible() {
return glob("**/*.less", function (err, files) {
if (err) {
return false;
}

return true;
})
}

Answer

The following does not work

Yes. It absolutely cannot work.

If the caller of isEligible (i.e. the build package) does not support asynchrony, then you have to make your function synchronous, there is no way around it. You might file a feature request for providing a callback to isEligible or accepting a promise as the return value, though.