关于Promise的一个测试题

2021-12-01  本文已影响0人  硅谷干货

我们知道Promise是一个高阶函数,Promise可以作为参数继续传参Promise,那么我出这样一道题你会不会绕进去呢?希望你没有!

第一题的重点:练习返回一个resolve

function foo() {
  return Promise.resolve('aaa')
          .then(data => { console.log("then1: ", data); })
          .then(data => { console.log("then2: ", data); return 'bbb'; })
          .then(data => { console.log("then3: ", data); return Promise.resolve('ccc'); })
          .catch(err => { console.log("eee"); return Promise.reject('eee'); });
}

console.log("111")
foo()
  .then(data => { console.log("333: ", data); })
  .catch(err => { console.log("eee"); return 'ggg' });
console.log("222")

第二题的重点:练习返回一个reject

function foo() {
  return Promise.resolve('aaa')
          .then(data => { console.log("then1: ", data); })
          .then(data => { console.log("then2: ", data); return 'bbb'; })
          .then(data => { console.log("then3: ", data); return Promise.reject('ccc'); })
          .catch(err => { console.log("eeee1: ", err);  return Promise.reject('ddd'); });
}

console.log("111")
foo()
  .then(data => { console.log("333: ", data); })
  .catch(err => { console.log("eeee2"); return 'ggg' });
console.log("222")

到这里,我建议你先不要直接拷贝到编辑器运行,而是稍作思考,然后直接把答案写出来,再运行也不迟,如果运行结果和你手写的一样,那么恭喜你,你已经完全掌握了

好了,答案我会放到最后,接下来先复习两个重要知识点:

高阶函数

如果一个函数符合下面2个规范中的任何一个,那该函数就是高阶函数

函数的柯里化

通过函数调用继续返回函数的方式,实现多次接收参数最后统一处理的函数编码形式。

最后直接抛出答案:

第一题答案:

$ node test.js 
111
222
then1:  aaa
then2:  undefined
then3:  bbb
333:  ccc

第二题答案:

$ node test.js 
111
222
then1:  aaa
then2:  undefined
then3:  bbb
eeee1:  ccc
eeee2

点赞加关注,永远不迷路
每天一更新,创作拿命拼

上一篇 下一篇

猜你喜欢

热点阅读