【问题标题】:Retrieve value of variable outside function检索函数外变量的值
【发布时间】:2018-09-02 19:09:51
【问题描述】:

我想检索function(response) 之外的变量值。我能怎么做?请帮忙!

<script>

    Test();

    function Test(){
      var c = "";
      filter();

      function filter(data) {
        c = data;
        console.log(data);
      }

       var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
       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);
          filter(response[0].name);
       });

    }

</script>

我的结果是用"dara@" 找到但undefined 是这样的:

undefined
"dara@"

【问题讨论】:

  • 好吧 .... 函数测试没有返回任何东西 - 即undefined

标签: javascript promise fetch fetch-api


【解决方案1】:

您应该等待 promise 成功回调('then' 函数)来打印结果。

Test();

function Test() {
  query().then(function(ret) {
    console.log(ret)
  })

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

【讨论】:

    【解决方案2】:

    一个选项是await它:

    Test();
    async function Test(){
      var c = "";
      filter();
      function filter(data) {
        c = data;
        console.log(data);
      }
    
       var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
       const responseJSON = fetch(url)
         .then(response => response.json()) 
         .then((responseJSON) => {
            //console.log('Success:', response[0].name);
            filter(responseJSON[0].name);
            return responseJSON;
         })
         .catch(error => console.error('Error:', error))
        console.log(`got ${responseJSON}`);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多