简体   繁体   English

从其父级的异步函数返回值

[英]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. 我正在为Atom文本编辑器创建构建提供程序,该编辑器是基于build软件包的组件。 This package allows you to run some tests to check whether a provider is eligible to run or not, returning true or false respectively. 该软件包允许您运行一些测试以检查提供程序是否有资格运行,分别返回truefalse

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. 我正在使用glob来检查项目文件夹中是否存在某种文件类型,以确定是否激活构建提供程序。 For example, a project folder should include a LESS file in order to activate a build provider for lessc . 例如,项目文件夹应包含LESS文件,以便为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() . 我想知道异步使用glob是否可以实现相同的目的,特别是我如何从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: 由于该函数正在异步执行,因此return语句将不起作用,而您需要做的是使用回调,即:

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. 如果主叫方isEligible (即build包)不支持异步,那么你必须让你的功能同步,有没有办法解决它。 You might file a feature request for providing a callback to isEligible or accepting a promise as the return value, though. 不过,您可能会提出功能请求,以提供对isEligible的回调或接受promise作为返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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