TypeError: func(…).then is not a function报错解决方法

今天想自己实现一个js中promise函数 then()的实现,所以就写了下面的例子,结果却报错:TypeError: func(…).then is not a function

错误例子

const func = (a, b) => {

  let operand1 = a * 10;
  let operand2 = b * 10;

  return operand1 + operand2
};

const funcwrapper = (a, b) => {
  func(a, b).then((sum) => {
    if (sum == 0) {
      window.alert("value is zero");
    } else {
      window.alert(("sum is " + sum));
    }
  })
};

funcwrapper(5, 5);

所以各种寻找,发现是因为需要一个函数返回promise才能实现then,所以下面是正确的例子

正确代码

const func = (a, b) => {

  let operand1 = a * 10;
  let operand2 = b * 10;

  return new Promise((resolve, reject) => resolve(operand1 + operand2));
};

const funcwrapper = (a, b) => {
  func(a, b).then((sum) => {
    if (sum == 0) {
      window.alert("value is zero");
    } else {
      window.alert(("sum is " + sum));
    }
  })
};

funcwrapper(5, 5);

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理