代码之家  ›  专栏  ›  技术社区  ›  Mevia

异步并等待以下获取请求

  •  0
  • Mevia  · 技术社区  · 6 年前

    async , await . 唯一的问题是,在我当前的设置中,我对如何编写它有点困惑。

    设置如下:

    1. 我点击一个按钮触发 clicker 作用
    2. 点击器 ajax
    3. 功能是 fetch 要求
    4. 点击器 作用

    目前我正在 undefined 功能,有人能帮忙指出问题所在吗?

    var ajax = function() {
    	fetch('https://jsonplaceholder.typicode.com/todos/1')
    		.then(response => response.json())
    		.then(json => { console.log('ajax function', json); return json; })
    		.catch(error => console.log(error))
    };
    
    var clicker = async function() {
    	var a = await ajax();
    	console.log('clicker function', a);
    };
    <div onclick="clicker(event, this);">
    	Test Me
    </div>
    2 回复  |  直到 6 年前
        1
  •  2
  •   Kamil Kiełczewski    6 年前

    尝试

    var ajax = async function() {
      try {
        let response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
        let json = await response.json();
        console.log('ajax function', json)
        return json;
    
      } catch (error) {
        console.log(error)
      };
    };
    
    var clicker = async function() {
      var a = await ajax();
      console.log('clicker function', a);
    };
    .btn { border-radius: 5px; background: #00ff00; width: 80px; padding: 10px;cursor: pointer; }
    <div class="btn" onclick="clicker(event, this);">
      Test Me
    </div>
        2
  •  0
  •   Quentin    6 年前

    你只能 await 承诺。

    的返回值 ajax() undefined 因为它没有返回语句。

    fetch

    添加返回语句:

    return fetch('https://jsonplaceholder.typicode.com/todos/1')