To pass parameters to a Promise function in JavaScript, you can define the function to take parameters as arguments, and use those arguments in the Promise body.
Here’s an example of a Promise function that takes two parameters x
and y
:
function add(x, y) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (typeof x !== 'number' || typeof y !== 'number') {
return reject(new Error('Both arguments should be numbers'));
}
resolve(x + y);
}, 1000);
});
}
add(2, 3)
.then(sum => {
console.log(sum); // 5
})
.catch(error => {
console.error(error);
});
In this example, the add
function takes two parameters x
and y
. It returns a Promise that resolves with the sum of x
and y
after a one-second delay, or rejects with an error if either x
or y
is not a number. To use the add
function, we call it with two arguments, and use the then
method to handle the resolved value, or the catch
method to handle the rejected error.
+ There are no comments
Add yours