JavaScript promise基础示例

const { info } = console
// cooking
function cook() {
  info('[COOKING] start cooking.')
  const p = new Promise((resolve, reject) => {
    setTimeout(() => {
      info('[COOKING] complete cooking.')
      resolve('[RESOLVE from cook]: rice with egg.')
    }, 1000);
  })
  return p
}

function eat(food) {
  info('[EATING] start eating.' + food)
  const p = new Promise((resolve, reject) => {
    setTimeout(() => {
      info(`[EATING] complete eating`)
      resolve('[RESOLVE from eat]: you should washing bowls and chopsticks.')
    }, 1000);
  })
  return p
}
// cook 方法中返回了一个 Promise,使用then查看返回结果
const promise_cook = cook()
// 将cook返回的结果作为参数传递给eat
const promise_eat = promise_cook.then(food => eat(food))
// eat 方法中返回了一个 Promise,使用then查看返回结果
promise_eat.then(res => {
  return new Promise((resolve, reject) => {
    resolve(`[Washing] ${res} done`)
  })
}).then((msg) => {
  console.info(msg)
})
posted @ 2020-07-21 09:16  荣光无限  阅读(246)  评论(0编辑  收藏  举报