Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand JavaScript Promise

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to understand JavaScript Promise, in view of this problem, this article introduces the corresponding analysis and answers in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

In general, in development, querying network API operations is often time-consuming, which means it may take some time to wait to get a response. Therefore, in order to avoid the situation that the program does not respond to the request, asynchronous programming has become a basic skill of developers.

When dealing with asynchronous operations in JavaScript, we often hear the concept of "Promise". However, it may be abstract and difficult to understand how it works and how to use it.

Example 1: explain the basics of Promise with birthdays

First of all, let's take a look at the basic form of Promise.

Promise execution time is divided into three states: pending (in progress), fulfilled (success), and rejected (failure).

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

New Promise (function (resolve, reject) {

If (/ * Asynchronous operation succeeded * /) {

Resolve (value); / / change the status of Promise from padding to fulfilled

} else {

Reject (error); / / change the status of Promise from padding to rejected

}

})

There are three prototype methods: then, catch, and finally.

Promise

.then ((result) = > {

/ / promise is accepted or refused to continue execution

})

. Catch ((error) = > {

/ / circumstances in which promise was rejected

})

.finally () = > {

/ / when the promise is completed, it will be executed anyway

})

The basic morphological introduction is complete, so let's take a look at the following example.

User story: my friend Kayo promised to make me a cake on my birthday Party in two weeks' time.

If all goes well and Kayo is not sick, we will get a certain amount of cake, but if Kayo is sick, we will have no cake. But with or without cake, we will still have a birthday Party.

So for this example, let's translate the background story above into JS code, let's first create a function that returns Promise.

one

two

three

four

five

six

seven

eight

nine

ten

eleven

Const onMyBirthday = (isKayoSick) = > {

Return new Promise ((resolve, reject) = > {

SetTimeout () = > {

If (! isKayoSick) {

Resolve (2)

} else {

Reject (new Error ("I am sad"))

}

}, 2000)

});

}

In JavaScript, we can use new Promise () to create a new Promise that accepts a function with an argument of: (resolve,reject) = > {}.

In this function, resolve and reject are the callback functions provided by default. Let's take a closer look at the code above.

When we run the onMyBirthday function 2000ms.

If Kayo is not sick, then we will execute the resolve function with the argument 2

If Kayo is sick, we execute reject with new Error ("I am sad") as a parameter. Although you can pass anything you want to reject as a parameter, it is recommended that you pass it to the Error object.

Now, because onMyBirthday () returns a Promise, we can access the then, catch, and finally methods. We can also access the parameters passed to resolve and reject in then and catch earlier.

Let's understand the concept with the following code

If Kayo wasn't sick,

one

two

three

four

five

six

seven

eight

nine

ten

OnMyBirthday (false)

.then ((result) = > {

Console.log (`I have ${result} cakes`); / / the console prints "I have 2 cakes"

})

. Catch ((error) = > {

Console.log (error); / / do not execute

})

.finally () = > {

Console.log ("Party"); / / print "Party" on the console

});

If Kayo gets sick,

one

two

three

four

five

six

seven

eight

nine

ten

OnMyBirthday (true)

.then ((result) = > {

Console.log (`I have ${result} cakes`); / / do not execute

})

. Catch ((error) = > {

Console.log (error); / / console prints "I'm sorry"

})

.finally () = > {

Console.log ("Party"); / / print "Party" on the console

});

I believe you can understand the basic concepts of Promise through this example.

Let's start with example 2.

Example 2: a game of guessing numbers

Basic requirements:

The user can enter any number

The system randomly generates a number from 1 to 6

If the user input number is equal to the system random number, give the user 2 points

If the difference between the user's input number and the system random number is 1, give the user 1 point, otherwise, give the user 0 point.

Users can play as long as they want.

For the above requirements, we first create an enterNumber function and return a Promise:

one

two

three

four

five

Const enterNumber = () = > {

Return new Promise ((resolve, reject) = > {

/ / start coding from here

});

}

The first thing we need to do is to ask the user for a number and choose a number randomly between 1 and 6:

one

two

three

four

five

six

Const enterNumber = () = > {

Return new Promise ((resolve, reject) = > {

Const userNumber = Number (window.prompt ("Enter a number (1-6):")); / / ask the user for a number

Const randomNumber = Math.floor (Math.random () * 6 + 1); / / Select a random number from 1 to 6

});

}

When the user enters a value that is not a number. In this case, we call the reject function and throw an error:

one

two

three

four

five

six

seven

eight

nine

ten

Const enterNumber = () = > {

Return new Promise ((resolve, reject) = > {

Const userNumber = Number (window.prompt ("Enter a number (1-6):")); / / ask the user for a number

Const randomNumber = Math.floor (Math.random () * 6 + 1); / / Select a random number from 1 to 6

If (isNaN (userNumber)) {

Reject (new Error ("Wrong Input Type")); / / when the value entered by the user is non-numeric, throw an exception and call the reject function

}

});

}

Next, we need to check whether userNumber is equal to RanomNumber, and if so, we give the user 2 points, and then we can execute the resolve function to pass an object {points: 2, randomNumber} object.

If the difference between userNumber and randomNumber is 1, then we give the user 1 point. Otherwise, we give the user a score of 0.

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

Return new Promise ((resolve, reject) = > {

Const userNumber = Number (window.prompt ("Enter a number (1-6):")); / / ask the user for a number

Const randomNumber = Math.floor (Math.random () * 6 + 1); / / Select a random number from 1 to 6

If (isNaN (userNumber)) {

Reject (new Error ("Wrong Input Type")); / / when the value entered by the user is non-numeric, throw an exception and call the reject function

}

If (userNumber = randomNumber) {

/ / if equal, we will give the user 2 points.

Resolve ({

Points: 2

RandomNumber

});

} else if (

UserNumber = randomNumber-1 | |

UserNumber = randomNumber + 1

) {

/ / if the difference between userNumber and randomNumber is 1, then we will give the user 1 point.

Resolve ({

Points: 1

RandomNumber

});

} else {

/ / otherwise, the user will get 0 points.

Resolve ({

Points: 0

RandomNumber

});

}

});

Next, let's create another function to ask the user if they want to continue the game:

one

two

three

four

five

six

seven

eight

nine

Const continueGame = () = > {

Return new Promise ((resolve) = > {

If (window.confirm ("Do you want to continue?") {/ / ask the user if you want to continue the game.

Resolve (true)

} else {

Resolve (false)

}

});

}

In order not to force the end of the game, the Promise we created did not use a Reject callback.

Next, let's create a function to handle the guessing logic:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

Const handleGuess = () = > {

EnterNumber () / / returns a Promise object

.then ((result) = > {

Alert (`Dice: ${result.randomNumber}: you got ${result.points} points`); / / when resolve runs, we get user scores and random numbers

/ / ask the user if you want to continue the game

ContinueGame () .then ((result) = > {

If (result) {

HandleGuess (); / / If yes, the game continues

} else {

Alert ("Game ends"); / / If no, pop up the game end box

}

});

})

. Catch ((error) = > alert (error))

}

HandleGuess (); / / execute the handleGuess function

When we call the handleGuess function here, enterNumber () returns a Promise object.

If the Promise status is resolved, we call the then method, inform the user of the guessing result and score, and ask the user if we want to continue the game.

If the Promise status is rejected, we will display a user input error message.

However, although such code can solve the problem, it is still a bit difficult to read. Let's ReFactor hanldeGuess using async/await later.

There are many explanations for async/await on the Internet, and here I would like to use a simple summary to explain: async/await is the syntax sugar that can turn complex asynchronous code into synchronous syntax.

Let's start to look at the reconstructed code:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

Const handleGuess = async () = > {

Try {

Const result = await enterNumber (); / / instead of the then method, we can get the result directly by placing the await in front of the promise

Alert (`Dice: ${result.randomNumber}: you got ${result.points} points`)

Const isContinuing = await continueGame ()

If (isContinuing) {

HandleGuess ()

} else {

Alert ("Game ends")

}

} catch (error) {/ / catch method can be replaced by try and catch functions

Alert (error)

}

}

By using the async keyword before the function, we create an asynchronous function that is used differently within the function than before:

Unlike the then function, we can get the result directly by placing the await keyword in front of the Promise.

We can use try, catch syntax instead of the catch method in promise.

The following is our complete refactored code for reference:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

thirty-two

thirty-three

thirty-four

thirty-five

thirty-six

thirty-seven

thirty-eight

thirty-nine

forty

forty-one

forty-two

forty-three

forty-four

forty-five

forty-six

forty-seven

forty-eight

forty-nine

fifty

fifty-one

fifty-two

fifty-three

fifty-four

fifty-five

fifty-six

57

58

59

sixty

Const enterNumber = () = > {

Return new Promise ((resolve, reject) = > {

Const userNumber = Number (window.prompt ("Enter a number (1-6):")); / / ask the user for a number

Const randomNumber = Math.floor (Math.random () * 6 + 1); / / the system randomly selects a number from 1 to 6.

If (isNaN (userNumber)) {

Reject (new Error ("Wrong Input Type")); / / throw an error if the user enters a non-numeric number

}

If (userNumber = randomNumber) {/ / if the user guesses the number correctly, give the user 2 points

Resolve ({

Points: 2

RandomNumber

});

} else if (

UserNumber = randomNumber-1 | |

UserNumber = randomNumber + 1

) {/ / if the difference between userNumber and randomNumber is 1, then we will give the user 1 point

Resolve ({

Points: 1

RandomNumber

});

} else {/ / incorrect, score 0

Resolve ({

Points: 0

RandomNumber

});

}

});

}

Const continueGame = () = > {

Return new Promise ((resolve) = > {

If (window.confirm ("Do you want to continue?") {/ / ask the user if you want to continue the game.

Resolve (true)

} else {

Resolve (false)

}

});

}

Const handleGuess = async () = > {

Try {

Const result = await enterNumber (); / / await replaces the then function

Alert (`Dice: ${result.randomNumber}: you got ${result.points} points`)

Const isContinuing = await continueGame ()

If (isContinuing) {

HandleGuess ()

} else {

Alert ("Game ends")

}

} catch (error) {/ / catch method can be replaced by try and catch functions

Alert (error)

}

}

HandleGuess (); / / execute the handleGuess function

Now that we have completed the second example, let's look at the third example.

Example 3: get country information from Web API

Generally, when getting data from API, developers will make good use of Promises. If you open https://restcountries.eu/rest/v2/alpha/cn in a new window, you will see country data in JSON format.

By using Fetch API, we can easily get the data. Here is the code:

one

two

three

four

five

six

seven

eight

nine

Const fetchData = async () = > {

Const res = await fetch ("https://restcountries.eu/rest/v2/alpha/cn"); / / fetch () returns a promise, so we need to wait for it

Const country = await res.json (); / / res is now only an HTTP response, so we need to call res.json ()

Console.log (country); / / China's data will be logged to the dev console

}

FetchData ()

Now that we have the required country data, let's move on to the last task.

Example 4: get a list of neighboring countries of a country from Web API

The following fetchCountry function gets the country information from the api in example 3, where the parameter alpha3Code is the country code that refers to the country. Here is the code

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

/ / Task 4: get information about neighboring countries around China

Const fetchCountry = async (alpha3Code) = > {

Try {

Const res = await fetch (

`https: / / restcountries.eu/rest/v2/alpha/$ {alpha3Code} `

);

Const data = await res.json ()

Return data

} catch (error) {

Console.log (error)

}

}

Let's create a fetchCountryAndNeighbors function to get the information about China by passing cn as alpha3code.

one

two

three

four

five

six

seven

Const fetchCountryAndNeighbors = async () = > {

Const china= await fetchCountry ("cn")

Console.log (china)

}

FetchCountryAndNeighbors ()

In the console, let's look at the contents of the object:

In the object, there is a border attribute, which is the alpha3codes list of China's neighboring countries.

Now, if we try to obtain information about neighboring countries in the following ways.

one

two

Const neighbors =

China.borders.map ((border) = > fetchCountry (border))

Neighbors is an array of Promise objects.

When dealing with the Promise of an array, we need to use Promise.all.

one

two

three

four

five

six

seven

eight

nine

ten

eleven

Const fetchCountryAndNeigbors = async () = > {

Const china = await fetchCountry ("cn")

Const neighbors = await Promise.all (

China.borders.map ((border) = > fetchCountry (border))

);

Console.log (neighbors)

}

FetchCountryAndNeigbors ()

In the console, we should be able to see a list of country objects.

The following is all the code for example 4 for your reference:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

Const fetchCountry = async (alpha3Code) = > {

Try {

Const res = await fetch (

`https: / / restcountries.eu/rest/v2/alpha/$ {alpha3Code} `

);

Const data = await res.json ()

Return data

} catch (error) {

Console.log (error)

}

}

Const fetchCountryAndNeigbors = async () = > {

Const china = await fetchCountry ("cn")

Const neighbors = await Promise.all (

China.borders.map ((border) = > fetchCountry (border))

);

Console.log (neighbors)

}

FetchCountryAndNeigbors ()

After completing these four examples, you can see that Promise is useful for dealing with asynchronous operations or things that do not happen at the same time.

The answer to the question on how to understand JavaScript Promise is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report