Hi Friends 👋,
Welcome To Infinitbility! ❤️
To pass parameters to a promise function in javascript, create a parameter function and use promise in a function like the below example.
var getNameById = function (id) {
return new Promise(function (resolve, reject) {
// ...
});
};
getNameById(3).then(function (res) {
console.log(res);
});
// output: "Stuff worked"
Today, I’m going to show you How do I pass parameters to a promise function in javascript, as above mentioned, I’m going to use the above-mentioned syntax to create and use a promise function with a parameter.
Let’s start today’s tutorial how do you pass parameters to a promise function in javascript?
Javascript promise function with parameter example
Here we will create a parameter function and store it in a variable, in the function we will create a promise with a resolve & reject option where we will check if it is greater than 0 resolve promise or rejects.
var getNameById = function (id) {
return new Promise(function (resolve, reject) {
if (id > 0) {
resolve('Stuff worked!');
} else {
reject(Error('It broke'));
}
});
};
getNameById(3).then(function (res) {
console.log(res);
});
// output: "Stuff worked"
ECS 6 promise function with parameter example
Same like javascript we can create a promise function with parameters in ECMAScript 6 also, there is only one difference we don’t need to mention the function keyword for creating a function.
let’s take an example.
const getNameById = (id) => {
return new Promise((resolve, reject) => {
if (id > 0) {
resolve('Stuff worked!');
} else {
reject(Error('It broke'));
}
});
};
getNameById(3).then(function (res) {
console.log(res);
});
// output: "Stuff worked"
I hope it helps you, All the best 👍.