今天想自己实现一个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);
发表回复