Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

异步任务:依次发送3次网络请求,拿到服务器数据

Sunny-117 opened this issue · comments

commented
异步任务:依次发送3次网络请求,拿到服务器数据
function data1() {
        return new Promise((res) => {
          setTimeout(() => {
            res("获取到第一条数据");
          }, 3000);
        });
      }
      function data2(data = "") {
        return new Promise((res) => {
          console.log(data);
          setTimeout(() => {
            res("获取到第二条数据");
          }, 5000);
        });
      }
      function data3(data = "") {
        return new Promise((res) => {
          console.log(data);
          setTimeout(() => {
            res("获取到第三条数据");
          }, 1000);
        });
      }
      function data4(data = "") {
        return new Promise((res, rej) => {
          console.log(data);
          rej(new Error("失败"));
        });
      }
      //   下一个接口需要上一个接口的数据 依次执行
      data1()
        .then((res) => {
          return data2(res);
        })
        .then((res) => {
          return data3(res);
        })
        .then((res) => {
          return data4(res);
        })
        .catch((err) => {
          console.log(err);
        });
      // 执行所有的异步任务 同时请求 成功
      const promises = [data1(), data2(), data3()];
      Promise.all(promises)
        .then((res) => {
          console.log("所有异步任务已成功加载");
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
      //  执行所有的异步任务 同时请求  失败
      Promise.all([...promises, data4()])
        .then((res) => {
          console.log("所有异步任务已成功加载");
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
commented

同时请求可以换种优雅的方式写法:
假设我们有3个请求,分别耗时一秒,在执行其他操作之前必须拿到三个结果,可以这么实现

const p1 = () => new Promise((resolve) => setTimeout(() => {
    resolve("p1");
}, 1000))
const p2 = () => new Promise((resolve) => setTimeout(() => {
    resolve("p2");
}, 1000))
const p3 = () => new Promise((resolve) => setTimeout(() => {
    resolve("p3");
}, 1000))


const fn = async () => {
    const r1 =  p1()
    const r2 =  p2()
    const r3 =  p3()

    const res1 = await r1
    const res2 = await r2
    const res3 = await r3

    console.log(res1, res2, res3)
}

这个应该是实现的promise.all的功能吧 貌似题目要求是要依赖上一个请求的结果