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

28次阅读

共计 618 个字符,预计需要花费 2 分钟才能阅读完成。

今天想自己实现一个 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);
正文完
 0