Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js promise async和await用法

作者:刃起风啸凌   发布日期:2026-07-14   浏览:54

// 使用 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();

解释说明:

  1. Promise:

    • resolveAfter2Seconds 是一个返回 Promise 的函数,它会在 2 秒后解析传入的值。
  2. async/await:

    • async 关键字用于定义一个异步函数,该函数会返回一个 Promise
    • await 关键字用于等待一个 Promise 解析,暂停函数执行直到 Promise 解析完成。
  3. add1 函数:

    • 这是一个异步函数,它调用了两个 resolveAfter2Seconds 函数,并等待它们的结果。最终返回 x + a + b 的和。
  4. fetchData 函数:

    • 这个函数展示了如何使用 async/await 处理网络请求,并捕获可能发生的错误。

上一篇:js substring

下一篇:nodejs async await

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站