[简明JavaScript]之Promise

简明 JavaScript 系列是我自己学习 JavaScript 概念时的笔记,旨在记录学习资料以及自己在实践中的感想。每一期尽量有一个有趣的 Demo 。

const readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

// 请原谅我这庸俗的剧情
said('Alice', "Will you always be here with me?")
said('Bob', "Oh dear Alice, why would I ever want to leave you?")
said('Alice', "Promise me!")

let promise = makePromise()

promise
  .then(() => {
    console.log('Alice and Bob were happy ever after.')
  })
  .catch(e => {
    console.log('Bob eventually left Alice, what a jerk.')
  })

function said (who, words) {
  console.log(`${who} said: ${words}`)
}

// 到了这里会有一个问题,试着跑一下?
function makePromise () {
  said('Bob', 'I promise I would never leave you.')
  return new Promise(function (resolve, reject) {
    rl.question('你来决定故事的走向: ', answer => {
      if (answer === 'good')
        return resolve('Bob is true to his words')
      return reject('Bob is a total ass')
    })
  })
}

女士们,先生们,看到了吗,这就是我们今天的主角 Promise。照例,以下是学习资料: