0

I'm working on a build provider for the Atom text editor, which is a component based on the build 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;
    })
}
idleberg
  • 12,634
  • 7
  • 43
  • 70

2 Answers2

0

As the function is executing asynchronously return statement won't work instead what you need to do is use callback ie:

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

      callback(true);
    })
}

Usage

//call isEligible

isEligible(function(result){
   //do something with result
});
AJS
  • 1,993
  • 16
  • 26
0

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • That explains why my previous attemps, similar to AJS's answer, don't work. Thanks for the explanation! – idleberg Nov 17 '16 at 17:20