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.
1var getNameById = function (id) {2 return new Promise(function (resolve, reject) {3 // ...4 });5};67getNameById(3).then(function (res) {8 console.log(res);9});1011// 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.
1var getNameById = function (id) {2 return new Promise(function (resolve, reject) {3 if (id > 0) {4 resolve('Stuff worked!');5 } else {6 reject(Error('It broke'));7 }8 });9};1011getNameById(3).then(function (res) {12 console.log(res);13});1415// 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.
1const getNameById = (id) => {2 return new Promise((resolve, reject) => {3 if (id > 0) {4 resolve('Stuff worked!');5 } else {6 reject(Error('It broke'));7 }8 });9};1011getNameById(3).then(function (res) {12 console.log(res);13});1415// output: "Stuff worked"
I hope it helps you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.