简体   繁体   中英

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 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;
    })
}

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
});

The following does not work

Yes. It absolutely cannot work .

If the caller of isEligible (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM