【问题标题】:Javascript: Get the value of a variable inside a function (fetch)Javascript:获取函数内变量的值(获取)
【发布时间】:2018-09-02 21:39:57
【问题描述】:

如何在function myFunc() 中获取变量data 的值?下面是我的代码的 sn-p。我想在这个实例var data = ret; 上检索一个值,以便在函数console.log(data) 之外使用。该代码返回一个带有ReferenceError: data is not defined 的错误。

myFunc();


   function myFunc() {
    query().then(function(ret) {
        console.log('result', ret); // result "@dara"
        var data = ret;
   });

    console.log(data); // ReferenceError: data is not defined
   }



  function query() {
    var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
    return fetch(url, {
        method: 'GET',
      })
      .then(function(response) {
        return response.json();
      })
      .catch(function(error) {
        console.error('Error:', error);
      })
      .then(function(response) {
        //console.log('Success:', response[0].name);
        return response[0].name;
      });

  }

【问题讨论】:

标签: javascript web promise fetch fetch-api


【解决方案1】:

var data = NULL or [] //添加到myfunc函数之外。

【讨论】:

    猜你喜欢
    • 2011-03-31
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多