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

使用 Promise 改写回调地狱 #144

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

使用 Promise 改写回调地狱 #144

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

Comments

@Sunny-117
Copy link
Owner

let t = setTimeout(() => {
    console.log(111);
    let t1 = setTimeout(() => {
        console.log(222);
        let t2 = setTimeout(() => {
            console.log(333);
        }, 3000);
    }, 2000);
}, 1000);

// todo
@mengqiuleo
Copy link

方式一:promise写法

function myPromise(time, context){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(context);
      resolve()
    }, time);
  })
}


// promise写法
myPromise(1000, 111)
  .then(() => {
    return myPromise(2000, 222);
  })
  .then(() => {
    return myPromise(3000, 333);
  })

方式二:

function myPromise(time, context){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(context);
      resolve()
    }, time);
  })
}

// async await写法
async function fun(){
  await myPromise(1000,111);
  await myPromise(2000,222);
  await myPromise(3000,333);
}
fun();

@tyust512
Copy link

new Promise((resolve) => {
  setTimeout(() => {
    console.log(111);
    resolve();
  }, 1000);
})
  .then(() => {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log(222);
        resolve();
      }, 2000);
    })
  })
  .then(() => {
    setTimeout(() => {
      console.log(333);
    }, 3000);
  });

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

3 participants