Navigate back to the homepage

how to pass parameter to a promise function in typescript?

Infinitbility
TypeScript
August 1st, 2022 · 1 min read
how to pass parameter to a promise function in typescript?

Hi Friends 👋,

Welcome To Infinitbility! ❤️

To pass parameters to a promise function in typescript, create a parameter function and use promise in a function like the below example.

1const getNameById = (id: number): Promise<string> => {
2 return new Promise(function (resolve, reject) {
3 // ...
4 })
5}

Today, I’m going to show you How do I pass parameters to a promise function in typescript, 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 typescript?

Typescript 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.

1const getNameById = (id: number): Promise<string> => {
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}
10
11let response: string = await getNameById(3);
12console.log(response)
13// 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.

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo Photoshop Guide

Tutorials

Categories

More articles from Infinitbility

how to check null value in json object in javascript?

how to check null value in json object in javascript?

An example of checking null value in JSON object in javascript with step by step guide.

July 31st, 2022 · 1 min read
how to set value in json object in javascript?

how to set value in json object in javascript?

An example of the set value in JSON object in javascript with step by step guide.

July 30th, 2022 · 1 min read
© 2020–2022 Infinitbility
About
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]