检索变量外部函数的值

时间:2018-03-24 03:41:07

标签: javascript promise fetch fetch-api

我想检索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@"

2 个答案:

答案 0 :(得分:0)

您应该等待承诺成功回调(&#39;然后&#39;函数)来打印结果。

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

答案 1 :(得分:0)

一个选项是await

&#13;
&#13;
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}`);
}
&#13;
&#13;
&#13;