I am a beginner of JavaScript. I am trying to understand the functions and promises in JS. I wrote a small code.
code Purpose: I wrote this code to understand the working of promise function(then
) on function with a return value.
input: a,b
output: if the sum of a & b is 0, then show the alert statement else show sum in the alert value.
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);
I am a beginner of JavaScript. I am trying to understand the functions and promises in JS. I wrote a small code.
code Purpose: I wrote this code to understand the working of promise function(then
) on function with a return value.
input: a,b
output: if the sum of a & b is 0, then show the alert statement else show sum in the alert value.
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);
I am still confused with this promise on functions with some return value after going through lot of investigation. So finally tried to implement the code to understand and got stuck with this error.
Please help me in understanding this topic.
Your help is appreciated. Thanks in advance
Share Improve this question edited Apr 17, 2020 at 5:21 Barmar 784k57 gold badges548 silver badges660 bronze badges asked Apr 17, 2020 at 5:13 rakrak 611 silver badge11 bronze badges 5- developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Teemu Commented Apr 17, 2020 at 5:14
-
1
func(a, b)
returns a number, not a promise. – Barmar Commented Apr 17, 2020 at 5:14 -
func()
needs to return a promise that resolves to the sum, not return the sum directly. – Barmar Commented Apr 17, 2020 at 5:16 - Thanks for the prompt reply. Can i convert this func into a promise? and work with the return value in then? – rak Commented Apr 17, 2020 at 5:17
- Could you please elaborate on it with the same example? – rak Commented Apr 17, 2020 at 5:18
1 Answer
Reset to default 7func()
needs to return a promise:
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);