Reactjs promises, how should we use it?

2019-04-06 05:23发布

问题:

I've been reading a lot about React for the last 3 days, but I don't see much information about the use of promises, so I have that concern.

Is there any library for this?

How should I use promises in React?

回答1:

React doesn't come with a promise library baked in like Angular with $http. You will have to find your own.

A few you can try:

  • Bluebird (personal recommendation)
  • jQuery's $ajax
  • Native promises (unless you actually have to support IE): http://caniuse.com/#feat=promises


回答2:

Promise object is used for handling asynchronous computations which has some important guarantees that are difficult to handle with the callback method (the more old-school method of handling asynchronous code).

A Promise object is simply a wrapper around a value that may or may not be known when the object is instantiated and provides a method for handling the value after it is known (also known as resolved) or is unavailable for a failure reason (we'll refer to this as rejected).

Using a Promise object gives us the opportunity to associate functionality for an asynchronous operation's eventual success or failure (for whatever reason). It also allows us to treat these complex scenarios by using synchronous.

To see more at : https://www.npmjs.com/package/react-promise