Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

Comments

@Sunny-117
Copy link
Owner

No description provided.

@hyxieshi
Copy link

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);
        });

@rhwoodpecker
Copy link

同时请求可以换种优雅的方式写法:
假设我们有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)
}

@Archill311
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants