ES6 JavaScript Promise objects (bottom)

Source: Internet
Author: User
Tags generator

5 Promise.all ()

The Promise.all method is used to wrap multiple Promise instances into a new Promise instance.
var p = promise.all ([p1, p2, p3]);
In the code above, the Promise.all method accepts an array as an argument, p1, p2, and P3 are instances of the Promise object, and if not, the Promise.resolve method described below is invoked to convert the argument to a Promise instance and further handle it. (The parameter of the Promise.all method can be not an array, but must have a iterator interface, and each returned member is a Promise instance.) )
The state of P is determined by P1, P2, p3 and divided into two situations.
(1) Only the state of P1, P2, P3 becomes fulfilled, the state of P becomes fulfilled, at which point the return values of P1, P2 and P3 form an array and pass to the callback function of P.
(2) As long as one of the P1, P2, P3 is rejected, the state of P becomes rejected, at which point the return value of the first instance that is reject is passed to the callback function of P.
The following is a concrete example.

  generates an array of Promise objects
var promises = [2, 3, 5, 7, one, 13].map (function (ID) {return
	Getjson ("/post/" + ID +). JSON ");
Promise.all (promises). Then (function (posts) {
	//...
}). catch (function (reason) {
	//...
});
In the code above, the promises is an array of 6 Promise instances, and only the states of these 6 instances become fulfilled, or if one of them becomes rejected, the callback function after the Promise.all method is invoked.
Here is another example.

Const Databasepromise = Connectdatabase ();
Const Bookspromise = Databaseproimse
	. then (findallbooks);
Const Userpromise = databasepromise
	. then (getcurrentuser);
Promise.all ([
		bookspromise,
		userpromise
	])
	. Then ([Books, user]) => picktoprecommentations ( Books, user));
In the code above, Bookspromise and Userpromise are two asynchronous operations that trigger Picktoprecommentations this callback function only until their results are returned.

6 Promise.race ()

The Promise.race method also wraps multiple Promise instances into a new Promise instance.

var p = promise.race ([p1, p2, p3]);
In the code above, as long as one instance of P1, P2, and P3 is the first to change the state, P's state changes. The return value of the Promise instance, which was first changed, is passed to the callback function of P.
The Promise.race method has the same parameters as the Promise.all method, and if it is not a Promise instance, it calls the Promise.resolve method described below and converts the argument to a Promise instance for further processing.
The following is an example, if the result is not obtained within the specified time, the Promise state is changed to reject, otherwise it becomes resolve.

var p = promise.race ([
	fetch ('/resource-that-may-take-a-while '),
	new Promise (function (resolve, reject) {
		settimeout (() => Reject (new Error (' Request timeout '), 5000)
	})
]
P.then (Response => Console.log (response))
P.catch (Error => console.log (error))
In the code above, if the Fetch method cannot return the result within 5 seconds, the state of the variable p becomes rejected, triggering the callback function specified by the Catch method.


7 Promise.resolve ()

Sometimes it is necessary to convert an existing object to a Promise object, and the Promise.resolve method plays this role.

var jspromise = promise.resolve ($.ajax ('/whatever.json '));
The above code converts the deferred object generated by JQuery to a new Promise object.
Promise.resolve is equivalent to the following notation.

Promise.resolve (' foo ')
	//  equivalent to
new Promise (Resolve => Resolve (' foo '))
The parameters of the Promise.resolve method are divided into four kinds of cases.
(1) The parameter is a Promise instance if the argument is an Promise instance, then Promise.resolve will not make any modifications and return the instance intact.
(2) parameter is a Thenable object
The Thenable object refers to an object that has a then method, such as the following object.

Let thenable = {
	then:function (resolve, reject) {
		resolve ();
	}
};
The Promise.resolve method converts the object to a Promise object, and then executes the then method of the Thenable object immediately.

Let thenable = {
	then:function (resolve, reject) {
		resolve ();
	}
};
Let P1 = Promise.resolve (thenable);
P1.then (function (value) {
	console.log (value);//
});
In the code above, after the then method of the Thenable object executes, the state of the object P1 becomes resolved, which immediately executes the callback function specified by the last then method, outputting 42.
(3) The parameter is not an object with the then method, or it is not an object at all
If the parameter is an original value, or an object that does not have an then method, the Promise.resolve method returns a new Promise object with a status of resolved.

var p = promise.resolve (' Hello ');
P.then (function (s) {
	console.log (s)
});
Hello
The above code generates an instance of the new Promise object p. Since the string hello does not belong to an asynchronous operation (the method is judged to be an object that is not a then method), the state that returns the Promise instance is resolved from one generation, so the callback function executes immediately. The parameters of the Promise.resolve method are passed to the callback function at the same time.
(4) without any parameters
The Promise.resolve method allows a call without arguments to return a Promise object with a resolved state directly.
Therefore, if you want to get a Promise object, the more convenient way is to call the Promise.resolve method directly.

var p = promise.resolve ();
P.then (function () {
	//...
});
The variable p of the above code is a Promise object.
Note that the immediate resolve Promise object is at the end of this round of event loop, not the beginning of the next round of event loops.

settimeout (function () {
	console.log (' three ');
}, 0);
Promise.resolve (). Then (function () {
	console.log (' two ');
});
Console.log (' one ');
One
//two
//three
In the code above, settimeout (FN, 0) executes at the beginning of the next round of "event loops", Promise.resolve () executes at the end of the "event loop", and Console.log (' one ') executes immediately, and therefore outputs first.


8 Promise.reject ()

The Promise.reject (reason) method also returns a new Promise instance, which has a state of rejected. Its parameter usage is exactly consistent with the Promise.resolve method.

var p = promise.reject (' error ');  equivalent to
var p = new Promise (resolve, Reject) => reject (' error ')
p.then (null, function (s) {
	consol E.log (s)
});
There  was a mistake.
The above code generates an instance p of the Promise object, the state is rejected, and the callback function executes immediately.


92 useful Additional methods

ES6 's Promise API provides not a lot of methods, and there are some useful ways to deploy it yourself. Here's how to deploy two methods that are not in ES6 but are useful.

9.1 Done ()

The Promise object's callback chain, whether it ends with a then method or a catch method, may not be caught if the last method throws an error (because the error inside the Promise does not bubble to the global). Therefore, we can provide a done method, always at the end of the callback chain, to ensure that any errors that may occur are thrown.

Asyncfunc ()
	. Then (F1)
	. catch (R1)
	. Then (F2)
	. Done ();
Its implementation code is fairly straightforward.

Promise.prototype.done = function (onfulfilled, onrejected) {
	this.then (onfulfilled, onrejected)
		. catch ( function (reason) {
			//  throws a global error
			settimeout (() => {
				throw reason
			}, 0);
		})
;
From the code above, the use of the Done method can be used like the then method, providing a callback function for the fulfilled and rejected States, or providing no arguments. However, the done will catch any errors that may occur and throw them to the global.


9.2 finally ()

The finally method is used to specify the action to be performed regardless of the final state of the Promise object. It differs from the done method by accepting a normal callback function as a parameter, which must be executed anyway.
The following is an example where the server uses Promise to process the request and then uses the finally method to turn off the server.

Server.listen (0)
	. Then (function () {
		//Run Test
	})
	. finally (Server.stop);
It is also very simple to implement.

Promise.prototype.finally = function (callback) {let
	P = This.constructor;
	Return This.then (
		value => p.resolve (Callback ()). Then (() => value), Reason => (P.resolve
		()). Then (() => {
			throw reason
		})
	);
In the code above, the callback function callback is executed regardless of whether the previous Promise is fulfilled or rejected.


10 Application

10.1 Loading pictures

We can write a picture of the load as a promise, once the load is completed, the promise state changes.

Const PRELOADIMAGE = function (path) {return
	new Promise (function (resolve, reject) {
		var image = new Image ();
		Image.onload = Resolve;
		Image.onerror = Reject;
		IMAGE.SRC = path;
	};


The combination of 10.2 generator function and Promise

Using the generator function to manage a process, you typically return a Promise object when you encounter an asynchronous operation.

function Getfoo () {return
	new Promise (function (resolve, reject) {
		resolve (' foo ');
	})
var g = function* () {
	try {
		var foo = yield Getfoo ();
		Console.log (foo);
	} catch (e) {
		console.log (e);
	}
};

function run (generator) {
	var it = generator ();

	function go [result] {
		if (result.done) return result.value;
		Return Result.value.then (function (value) {return go
			(it.next value);
		}, Function (Error) {Return to go
			( It.throw (Error))
	;} Go (It.next ());
}
Run (g);
In the generator function g of the above code, there is an asynchronous operation Getfoo, which returns a Promise object. Function run is used to process this promise object and call the next next method.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.