JavaScript错误“Uncaught TypeError: xxx(…).then is not a function”的原因和解决方法

详解javascript中出现“Uncaught TypeError: xxx(...).then is not a function”错误的原因和解决方法。

错误内容

例如下面的代码:

function add(x,y){
  return x + y;
};

add(1,2).then(value => {
  console.log(value);
});

错误信息

Uncaught TypeError: add(...).then is not a function

JavaScript错误“Uncaught TypeError: xxx(…).then is not a function”的原因和解决方法  第1张

错误原因

因为该函数不是“Promise”

JavaScript错误“Uncaught TypeError: xxx(…).then is not a function”的原因和解决方法  第2张

使用Promise

function add(x,y){
  return new Promise((resolve, reject) => {
    resolve(x + y);
  });
};

add(1,2).then(value => {
  console.log(value); // 3
});

执行结果

JavaScript错误“Uncaught TypeError: xxx(…).then is not a function”的原因和解决方法  第3张

本文来源:词雅网

本文地址:https://www.ciyawang.com/javascript-typeerror.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐