学习[前端]promise的thenable规范理解

123 阅读1分钟

自从ES6提出了Promise后,给我们的开发带来了极大的便利,其中最重要的特性莫过于Promise特性了。

众所周知,Promise将我们回调函数的回调地狱中解放出来,我们今天重点讲解一下Promise 的 thenable特性.

什么是thenable?

thenable指的是任何具有then函数的对象或方法。

const obj = {
    then(res,rej) {
        res
    }
}

那么方法或对象拥有thenable函数具体有什么用呢?

首先我们看下面的一个案例,我们首先申明了一个包含了then的对象thenableObj,使用了Promise.resolve执行了这个对象,我们最终在控制台输出了 800 这个数值。

const thenableObj = {
  then(f,r) {
    f({
      then(ff,rr) {
        ff(800)
      }
    })
  },
  cache(){
    console.log('cache')
  }
};

Promise.resolve(thenableObj).then(console.log); // 输出 800

那么为什么会输出800呢?

image.png 这里的大概意思就是说接受一个符合thenable规范的对象,可以执行内部的then函数并返回结果

那么我们就可以知道 promise 支持 thenable 形式的对象来实现then处理,

现在有一个场景,可以借助此方法实现,我们需要一个定时器,并且定时器不能使用promise来实现,对此我们可以借助thenable特性来实现该场景,代码如下

function sleep(ms) {
  return {
    then(resolve) {
      setTimeout(resolve,ms)
    }
  }
}


(async ()=>{
  console.log(1)
  await sleep(1000) // 等待 1000ms 输出 2
  console.log(2)
})();

最终测试结果也符合预期

这里为什么使用async await 呢?

因为async await只是Promise的语法糖特性。