【问题标题】:How to use the variable beyond it's scope in Javascript? [duplicate]如何在 Javascript 中使用超出其范围的变量? [复制]
【发布时间】:2020-06-01 05:14:45
【问题描述】:

我想使用超出其范围的“标签”变量,我该怎么做?我知道这不是一个好习惯,但我仍然想使用标签数组中的值。我尝试克隆变量,但范围问题仍然存在

const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        var labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
    })

    .catch(err => {
        console.error('ERROR: ', err);
    });

编辑 1: 我想这样使用标签

const client = new vision.ImageAnnotatorClient();
    // Performs label detection on the image file
    client
        .labelDetection(`${filename}`)
        .then(results => {
            var labels = results[0].labelAnnotations;

            console.log('Labels: ');
            labels.forEach(label => console.log(label.description));
        })

        .catch(err => {
            console.error('ERROR: ', err);
        });

console.log('Labels: ');
                labels.forEach(label => console.log(label.description));

但控制台显示错误“Cannot use undefined for forEach”

【问题讨论】:

  • 您应该从.then() 中返回标签。使用 async / await,您可以访问承诺范围之外的值。

标签: javascript arrays scope javascript-scope


【解决方案1】:

在承诺之外简单地定义labels

const client = new vision.ImageAnnotatorClient();
let labels = null;

// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
    })

    .catch(err => {
        console.error('ERROR: ', err);
    });

不确定你想在哪里使用它,但你只能在 promise 解决后才能使用它的值。在这种情况下,更好的方法是:



I want to use the "labels" variable beyond its scope, how can I do it ? I know its not a good practice but I still want to use the values in labels array. I tried cloning the variable but the scope issue persists

const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        var labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
        return labels;
    })

    .then(labels => {
        console.error('Some other usage for labels: ', labels);
    });


    .catch(err => {
        console.error('ERROR: ', err);
    });

【讨论】:

    【解决方案2】:

    您只能使用.then() 访问该值,或者当您在async 上下文中时,您可以在promise 之外访问该值:

    (async () => {
      const client = new vision.ImageAnnotatorClient();
      const labels = client
        .labelDetection(`${filename}`)
        .then(results => results[0].labelAnnotations)
        .catch(err => console.error('ERROR: ', err))
    
      console.log('Labels: ');
      labels.forEach(label => console.log(label.description));
    })()
    

    这是一个工作示例,其中getLabels 是您当前代码的替代品:

    (async () => {
      const fakeData = [{
        labelAnnotations: [
          { description: 'label 1' },
          { description: 'label 2' },
          { description: 'label 3' },
        ]
      }]
    
      const getLabels = () => new Promise(r => setTimeout(r, 1000, fakeData))
      const results = await getLabels()
      const labels = results[0].labelAnnotations
      
      console.log('Labels: ');
      labels.forEach(label => console.log(label.description));
    })()

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 2013-10-26
      • 2013-12-28
      • 2016-04-30
      • 1970-01-01
      相关资源
      最近更新 更多