简体   繁体   English

如何从该异步函数获得结果?

[英]How do I get the result from this async function?

Problem 问题

I'm trying to get the diskName value back from this.getDiskName('C:') and assign it to element['name'] : 我正在尝试从diskName this.getDiskName('C:')获取diskName值,并将其分配给element['name']

getDisksInfo () { 
  ...
  element['name'] = this.getDiskName('C:')
  ...
},

getDiskName (diskLetter) {
  if (process.platform == 'win32') {
    var exec = require('child_process').exec
    var cmd = `wmic logicaldisk where caption="${diskLetter}" get VolumeName`

    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log(err)
      }
      let diskName = stdout.split('\n')[1]
      return diskName
    })
  }
}

I tried doing this, but I keep getting different errors: 我尝试这样做,但是不断出现不同的错误:

getDiskName (diskLetter, callback) {
    ...
    exec(cmd, (err, stdout, stderr) => {
      if callback(null, () => {
        let diskName = stdout.split('\n')[1]
        return diskName
      })
    ...
}

Question

Could someone please explain how to return the value properly? 有人可以解释如何正确返回值吗?

Your problem is that you are missing either a callback coming into getDiskName() or a Promise() coming out. 您的问题是您缺少进入getDiskName()的回调或出现的Promise()

Since the Promise approach seems to be more popular nowadays, I'll go with that for this answer. 由于Promise方法在当今似乎更受欢迎,因此我将继续回答这个问题。

With a Promise approach, you need the function to return a Promise . 使用Promise方法,您需要该函数返回Promise In most cases, you just wrap all the code up in a Promise and return that: 在大多数情况下,您只需将所有代码包装在Promise并返回:

getDiskName(diskLetter) {
    return new Promise((resolve, reject) => {
      // rest of your code in the function
    });
}

Then, instead of your return , you'll call resolve() : 然后,您将调用resolve()而不是return

let diskName = stdout.split('\n')[1];
resolve(diskName)

And for your error, you'll call reject: 对于您的错误,您将调用拒绝:

if (err) {
  reject(err);
}

Then, in the function that uses it, you'll have to wait for the then() in your function: 然后,在使用它的函数中,您必须等待函数中的then()

this.getDiskName('C:').then(diskName => console.log(diskName))

The callback method is similar, you just pass in the callback into getDiskName and call it when you're ready. 回调方法与此类似,您只需将回调传递到getDiskName并在准备好时调用它。

This is a more idiomatic method to handle a case like this. 这是处理这种情况的更惯用的方法。 We'll pass a function in to getDiskName which takes the disk name (which is the return value) as a parameter. 我们将一个函数传递给getDiskName ,该函数将磁盘名称(即返回值)作为参数。

getDisksInfo () { 
  ...
  this.getDiskName('C:', function(diskName) {
    element['name'] = diskName;
  });
  // Note that code from here to the end doesn't have access
  // to element['name']
  ...
},

getDiskName (diskLetter, func) {
  if (process.platform == 'win32') {
    var exec = require('child_process').exec
    var cmd = `wmic logicaldisk where caption="${diskLetter}" get VolumeName`

    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log(err)
      }
      let diskName = stdout.split('\n')[1]
      func(diskName);
    })
  }
}

Now, this still might not work for you since perhaps you have code after the call which relies on knowing the diskName. 现在,这可能仍然对您不起作用,因为在调用之后您可能需要依靠知道diskName的代码。 In that case, you would probably roll that code into your anonymous function. 在这种情况下,您可能会将代码滚动到匿名函数中。 Perhaps getDisksInfo takes a function as a parameter instead. 也许getDisksInfo取一个函数作为参数。

This is the general pattern, you have to determine how it best fits in your program. 这是一般模式,您必须确定它最适合您的程序的方式。

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

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