JavaScript 如何创建异步函数
JavaScript的异步函数是独立于程序主线程运行的函数。这使得程序在异步函数运行时可以继续执行其他代码。使用async来声明异步函数,并使用await来暂停函数的执行直到特定的异步任务完成。
创建异步函数的方法
使用async关键字
创建异步函数的最简单方法是在函数声明之前使用async关键字。以下是语法:
语法
async function fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data);
}
在这个示例中,fetchData函数使用await关键字等待数据从服务器获取后再将其记录到控制台。
示例
以下是一个使用JavaScript中的异步函数从服务器获取数据并在HTML页面上显示数据的示例:
<!DOCTYPE html>
<html>
<head>
<title>async</title>
</head>
<body>
Click below button to see the result
<button id="get-data">Get</button>
<div id="data-box"></div>
<script>
// Asynchronous function to fetch data
async function fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/3');
const data = await response.json();
return data;
}
// Add click event listener to the button
const button = document.getElementById('get-data');
button.addEventListener('click', async () => {
// Call the asynchronous function
const data = await fetchData();
// Use the data to update the HTML
const dataBox = document.getElementById('data-box');
dataBox.innerHTML = `Id: {data.id}
Title:{data.title}</p>`;
});
</script>
</body>
</html>
在这个示例中,我们有一个HTML按钮,其id为”get-button”,还有一个带有id为”data-box”的div容器。我们添加了一个事件监听器到按钮上,所以当点击按钮时,它调用了异步函数fetchData,该函数使用fetch API从服务器检索数据。一旦数据返回,它被用来更新带有id为”data-box”的div容器的HTML内容,包括标题和检索到的数据的完成情况。
注意 - 上述代码的输出可能会随着时间的推移而有所不同,因为数据来自外部API。
使用Promise
另一种创建异步函数的方法是使用Promise对象。Promise是一个表示异步操作(或失败)的最终完成和其结果值的对象。
语法
function fetchData() {
return new Promise((resolve, reject) => {
fetch('yoururl.com')
.then(response => response.json())
.then(data => resolve(data))
.catch(error => reject(error));
});
}
在语法上,fetchData函数返回一个新的promise,该promise从服务器获取数据,并在成功时解决并返回数据,或在出现错误时拒绝并返回错误信息。使用 then 和 catch 方法来处理promise的解决和拒绝。
示例
以下是一个使用JavaScript中的promise从服务器获取数据并在HTML页面上显示的示例:
<html>
<body>
<p>Click below button to see the result
<button id="get-button">Get</button>
<div id="data-box"></div>
<script>
// Async promise function to fetch data
function fetchData() {
return new Promise((resolve, reject) => {
fetch('https://jsonplaceholder.typicode.com/todos/3')
.then(response => response.json())
.then(data => resolve(data))
.catch(error => reject(error));
});
}
// Add click event listener to the button
const button = document.getElementById('get-button');
button.addEventListener('click', () => {
// Call the promise
fetchData()
.then(data => {
// Use the data to update the HTML
const dataBox = document.getElementById('data-box');
dataBox.innerHTML = `Id: {data.id}
Status:{data.completed}</p>`;
})
.catch(error => console.log(error));
});
</script>
</body>
</html>
在这个示例中,我们有一个id为“get-button”的HTML按钮和一个id为“data-box”的div容器。我们给按钮添加了一个事件监听器,当点击按钮时,它会调用fetchData函数,该函数使用fetch API从服务器检索数据并返回一个Promise。一旦Promise被解决,它将被用来更新id为“data-box”的div容器的HTML内容,包括所检索到的数据的Id和已完成项目。如果Promise被拒绝,它将在控制台中记录错误。
注意 − 上述代码的输出可能会随着时间而不同,因为数据来自外部API。
使用async / await与Promise.all
Promise.all方法返回一个Promise,当作为可迭代对象的所有Promises都解决时,它将被解决,否则将以第一个被拒绝的Promise的原因拒绝。
语法
async function fetchData() {
const response = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]);
const data = await Promise.all(response.map(res => res.json()));
console.log(data);
}
在这个示例中,fetchData函数使用Promise.all方法从服务器获取多个数据,并用await关键字在将数据记录到控制台之前等待所有响应。
示例
以下是如何在JavaScript中使用async/await和Promise.all来从服务器获取多个数据并在HTML页面上显示的示例 –
<html>
<body>
<p>Click below button to see the result
<button id="get-button">Get</button>
<div id="data-box"></div>
<script>
// Asynchronous function to fetch data
async function fetchData() {
const response = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]);
const data = await Promise.all(response.map(res => res.json()));
return data;
}
// Add click event listener to the button
const fetchButton = document.getElementById('get-button');
fetchButton.addEventListener('click', async () => {
// Call the async function
const data = await fetchData();
// Use the data to update the HTML
const dataBox = document.getElementById('data-box');
dataBox.innerHTML = `
Id 1: {data[0].id}
Title 1:{data[0].title}
Status 1: {data[0].completed}
Id 2:{data[1].id}
Title 2: {data[1].title}
Status 2:{data[1].completed}
`;
});
</script>
</body>
</html>
在这个示例中,我们有一个id为“get-button”的HTML按钮和一个id为“data-box”的div容器。我们为按钮添加了事件监听器,所以当点击按钮时,它调用了异步函数fetchData,该函数使用fetch API和Promise.all方法从服务器检索多个数据。现在它使用await关键字等待所有响应返回数据,然后将检索到的数据的id、标题和完成项更新到id为“data-box”的div容器的HTML内容中。
注意 - 由于数据来自外部API,上述代码的输出可能会随时间而异。
结论
JavaScript提供了多种创建异步函数的方法,包括使用async关键字、Promise对象和async/await与Promise.all结合使用。每种方法都有自己的好处和用例。async关键字和await关键字用于执行需要很长时间才能完成的任务,例如从服务器获取数据等。