微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Promise的响应未正确返回json文件输出

如何解决Promise的响应未正确返回json文件输出

因此,在运行以下代码时,console.log(ba)的响应为undefined 但是,当我在Chrome V8控制台中尝试此操作时,会得到期望的正确输出。我不太确定这里发生了什么。

    let ba;
    
    function Setqa() {
      ( async() => {
          await fetch('questions.json')
            .then(res => res.json())
              .then(async(data) => {
                ba = await data;
            });
      })();
    }
    
    Setqa();
    
    console.log(ba);

json文件内容如下:

"questions": [{
            "questionType": "multiple","question": "How is the weather","answers": "","questionAnswer": ""
        },{
            "questionType": "multiple","question": "How are you today?","answers": "<textarea rows='5' class='textArea'></textarea>1","questionAnswer": "textPurpose1"
        }
    ]

解决方法

我想应该可以

    let ba;
    
    function Setqa() {
      return fetch('questions.json')
            .then(res => res.json())
              .then(async(data) => {
                ba = await data;
            });
    }
    
    Setqa().then( () => console.log(ba) );
    

但是更好的方法是

async function setQa(){
   const res = await fetch('questions.json');
   return res.json();
}

let ba = await setQa();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。