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

使用 Promise 改写回调地狱

Sunny-117 opened this issue · comments

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

// todo
commented

方式一: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();
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);
  });

const p = new Promise(resolve => {
setTimeout(() => {
console.log(111);
resolve()
}, 1000)
})

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