// 使用 Promise、async 和 await 的示例
// 创建一个返回 Promise 的函数
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
// 使用 async 定义异步函数
async function add1(x) {
// 使用 await 等待 Promise 解析
const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;
}
// 调用异步函数并处理结果
add1(10).then(result => {
console.log(result); // 输出: 60
});
// 另一个使用 async/await 的例子:处理错误
async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
let data = await response.json();
console.log(data);
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
// 调用 fetchData 函数
fetchData();
Promise:
resolveAfter2Seconds 是一个返回 Promise 的函数,它会在 2 秒后解析传入的值。async/await:
async 关键字用于定义一个异步函数,该函数会返回一个 Promise。await 关键字用于等待一个 Promise 解析,暂停函数执行直到 Promise 解析完成。add1 函数:
resolveAfter2Seconds 函数,并等待它们的结果。最终返回 x + a + b 的和。fetchData 函数:
async/await 处理网络请求,并捕获可能发生的错误。上一篇:js substring
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站