首页 > javascript > async并等待获取请求

async并等待获取请求 (async and await following fetch request)

2019-03-05 javascriptajax

问题

我正在尝试重新编写当前使用回调的代码asyncawait。唯一的问题是,在我目前的设置中,我对它应该如何编写有点困惑。

设置是:

  1. 我点击一个触发clicker功能的按钮
  2. clicker功能触发ajax功能
  3. ajax功能确实fetch要求
  4. 在响应回来之后,我需要将响应传递给clicker函数

目前我undefinedajax功能,可能有人帮助,并指出问题是什么?

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>


解决方法

尝试

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>


问题

I am trying to rework my code that currently uses callbacks to use async, await. The only thing is that in my current setup i am a little bit confused about how it should be written.

The setup is that:

  1. i click a button that triggers clicker function
  2. clicker function triggers ajax function
  3. ajax function does fetch request
  4. after response is back I need to pass response to clicker function

Currently I am getting undefined from ajax function, could someone help and point out what is the problem?

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>

解决方法

Try

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>

相似信息