美文网首页我爱编程
ES6 Promise的十道题

ES6 Promise的十道题

作者: silly鸿 | 来源:发表于2018-03-30 18:11 被阅读0次

    Promise 想必大家十分熟悉,想想就那么几个 api,可是你真的了解 Promise 吗?本文根据 Promise 的一些知识点总结了十道题,看看你能做对几道。

    以下 promise 均指代 Promise 实例,环境是 Node.js。

    题目一

    const promise = new Promise((resolve, reject) => {
      console.log(1)
      resolve()
      console.log(2)
    })
    promise.then(() => {
      console.log(3)
    })
    console.log(4)
    

    题目二

    const promise1 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('success')
      }, 1000)
    })
    const promise2 = promise1.then(() => {
      throw new Error('error!!!')
    })
    
    console.log('promise1', promise1)
    console.log('promise2', promise2)
    
    setTimeout(() => {
      console.log('promise1', promise1)
      console.log('promise2', promise2)
    }, 2000)
    

    题目三

    const promise = new Promise((resolve, reject) => {
      resolve('success1')
      reject('error')
      resolve('success2')
    })
    
    promise
      .then((res) => {
        console.log('then: ', res)
      })
      .catch((err) => {
        console.log('catch: ', err)
      })
    

    题目四

    Promise.resolve(1)
      .then((res) => {
        console.log(res)
        return 2
      })
      .catch((err) => {
        return 3
      })
      .then((res) => {
        console.log(res)
      })
    

    题目五

    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('once')
        resolve('success')
      }, 1000)
    })
    
    const start = Date.now()
    promise.then((res) => {
      console.log(res, Date.now() - start)
    })
    promise.then((res) => {
      console.log(res, Date.now() - start)
    })
    

    题目六

    Promise.resolve()
      .then(() => {
        return new Error('error!!!')
      })
      .then((res) => {
        console.log('then: ', res)
      })
      .catch((err) => {
        console.log('catch: ', err)
      })
    

    题目七

    const promise = Promise.resolve()
      .then(() => {
        return promise
      })
    promise.catch(console.error)
    

    题目八

    Promise.resolve(1)
      .then(2)
      .then(Promise.resolve(3))
      .then(console.log)
    

    题目九

    Promise.resolve()
      .then(function success (res) {
        throw new Error('error')
      }, function fail1 (e) {
        console.error('fail1: ', e)
      })
      .catch(function fail2 (e) {
        console.error('fail2: ', e)
      })
    

    题目十

    process.nextTick(() => {
      console.log('nextTick')
    })
    Promise.resolve()
      .then(() => {
        console.log('then')
      })
    setImmediate(() => {
      console.log('setImmediate')
    })
    console.log('end')
    

    结果

    执行结果及解释见原文作者的知乎文章:https://zhuanlan.zhihu.com/p/30797777

    延伸

    八段代码彻底掌握 Promise
    实例:promise.then如何处理连续ajax请求

    相关文章

      网友评论

        本文标题:ES6 Promise的十道题

        本文链接:https://www.haomeiwen.com/subject/tsnicftx.html