New Promise
New Promise (function function reject) resolver), Promise
Create a new promise, passing in a function that has two functions resolve, reject as arguments. These two parameter functions can be called in this function.
Example:
function ajaxgetasync (URL) { returnnew Promise (function (resolve, reject) { varnew XMLHttpRequest; Xhr.addeventlistener ("error", reject); Xhr.addeventlistener ("Load", resolve); Xhr.open ("GET", url); Xhr.send (null); });}
If you pass the Resovle function to the Promise object, the created promise will follow the status of the incoming promise.
To make sure a function that returns a promise are following the implicit but critically important contract of promises, yo u can start a function with new Promise
if you cannot start a chain immediately:
function getconnection (urlstring) { returnnew Promise (function(resolve) { //without new Promise, this throwing would throw an actual exception var params = Parse (urlstring); Resolve (Getadapter (params). getconnection ());} );
The above ensures getConnection
fulfills the contract of a promise-returning function of never throwing a synchronous exception. A LSO See and Promise.try
Promise.method
The resolver is called synchronously (the following are for documentation purposes and not idiomatic code):
function Getpromiseresolvefn () { var res; New Promise (function (resolve) { = resolve; }); // Res is guaranteed to BES set return Res;}
. Then
. Then ( [function(any value) Fulfilledhandler], [function- > Promise
. spread
. Spread ( [function-Promise
Like call. Then, but the passed value must be an array to expand the parameters of the fulfillment handler above.
Promise.delay. Then (function() { return [Fs.readfileasync ("File1.txt"), Fs.readfileasync ("File2.txt")];}). Spread (function(File1text, file2text) { if (file1text = = = File2text) { console.log ("files are equal"); } Else { console.log ("Files is not equal"); });
If you use ES6, the above code can use the. Then method instead
Promise.delay. Then (function() { return [Fs.readfileasync ("File1.txt"), Fs.readfileasync ("File2.txt")];}). All () and then (function([File1text, File2text]) { if (file1text = = = File2text) { console.log ("files are equal"); } Else { console.log ("Files is not equal"); });
Note: here. Spread is the equivalent of implicit invocation. All ()
If you want to coordinate several discrete concurrent promises, usePromise.join
. catch
. Catch is a convenient way to handle promise chains errors, it has two variants (usage), one catch-all similar to synchronous code block catch (E) {, which is compatible with native promise, A filtered variant (like other non-JS language typical features) that allows you to handle only specific errors, which is more reasonable and more secure.
Promise Handling Exceptions
Promise exception handling is modeled after native JavaScript exception handling, a synchronous function throw similar to Rejecting,catch in promise can be handled, as in the following example:
functionGetItems (Parma) {Try { varItems =Getitemssync (); if(!items)Throw NewInvaliditemserror (); } Catch(e) {//can address the error here, either from Getitemssync returning a Falsey value or throwing itself ThrowE//need to re-throw the error unless I want it to be considered handled. } returnprocess (items);}
The same, Promise.
functiongetItems (param) {returnGetitemsasync (). Then (items = { if(!items)Throw NewInvaliditemserror (); returnitems; }).Catch(E = { //can address the error here and recover from it, from Getitemsasync rejects or returns a Falsey value ThrowE//need to rethrow unless we actually recovered, just as in the synchronous version}). then (process);}
Catch-all
. Catch (function(any error) handler), Promise
. Caught (function(any error) handler), Promise
This is the catch-all exception handling handle, or it can be abbreviated. Then (Null,hanlder), which is handled in its most recent catch when any exception occurs in the. Then-chain.
In order to be compatible with the ES version, an alias is provided for catch caught
Filtered Catch
. Catch ( class Errorclass| function(any error) | Object predicate ..., function Promise
. Caught ( class Errorclass| function(any error) | Object predicate ..., function Promise
This approach is an extension to catch, like the catch usage in Java and C #, instead of a manual instanceof
or.name === "SomeError"来判断不同异常,
你可以对catch句柄指定一些合适的错误构造函数,这些catch句柄(hanlder)遇到合适的指定错误构造函数,catch句柄将会被调用,例如:
Somepromise.then (function() { returna.b.c.d ();}).Catch(TypeError,function(e) {//If It is a TypeError, would end up here because //It is a type error to reference property of undefined}).Catch(Referenceerror,function(e) {//Would end up here if A is never declared at all}).Catch(function(e) {//Generic catch-the Rest, error wasn ' t TypeError nor //Referenceerror});
Also add multiple filters for a catch handler:
You might add multiple exceptions to a catch handle:
Somepromise.then (function() { returna.b.c.d ();}).Catch(TypeError, Referenceerror,function(e) {//Would end up here on programmer error}).Catch(Networkerror, Timeouterror,function(e) {//Would end up here on expected everyday network errors}).Catch(function(e) {//Catch any unexpected errors});
If you filter the error (Specify to perform an error), the parameter must be confirmed to be the error type, and you need to construct the. Prototype property instanceof Error
.
As the following constructor example:
function= object.create (Error.prototype);
How to use
Promise.resolve (). Then (function() { thrownew mycustomerror ();}). Catch function (e) { //wouldendup here now});
Anyway, if you want to output detailed information and print stacks, support for node. JS and the latest V8 engineError.captureStackTrace
function mycustomerror (message) { this. Message = message; this. Name = "Mycustomerror"; Error.capturestacktrace (this == mycustomerror;
Use Coffeescript ' s class:
class Mycustomerror extends Error -- = "Mycustomerror" Error.capturestacktrace (this, mycustomerror)
This method also supports predicate-based filters (which supports predicate filters). If you pass a predicate functions instead of an error constructor (if the predicate function is passed in instead of the wrong constructor "What is the predicate function, as I understand the context: is the function that returns TRUE or false") , the predicate would receive the error as an argument. The return result of the predicate would be used determine whether the error handler should is called.
Predicates should allow to very fine grained control over caught errors:pattern matching, Error-type sets with set opera tions and many other techniques can is implemented on top of them.
Example of using a predicate-based filter:
var Promise = require ("Bluebird"); var request = Promise.promisify (Require ("request")); function Clienterror (e) { return e.code >= && e.code <;} Request ("http://www.google.com"). Then (function(contents) { console.log (contents);}). Catch function (e) { //A Client errorlike "happened}");
The predicate function only checks the attribute when the aspect shorthand, you can pass in the object to replace the predicate function, relies on the Error object match examines the object's property:
fs.readfileasync (...) . Then (...) . Catch function (e) { console.log ("File not found:" + E.path); });
The object predicate passed .catch
to the above code ( {code: ‘ENOENT‘}
) are shorthand for a predicate function function predicate(e) { return isObject(e) && e.code == ‘ENOENT‘ }
, i.e. loose E Quality is used.
By does returning a rejected value or throw
ing from a catch, you "recover from failure" and continue the chain:
If you do not return a rejected value or throw for a catch, you can "reset the error" and proceed to the chain.
Promise.reject (Error (' fail! ') )) . Catch (function(e) { // fallback with "Recover from failure" return // Promise or Value }) . Then (function(result) { // 'll print " Success! " });
This was exactly like the synchronous code:
var result; Try { throw Error (' fail 'catch(e) { = ' success! ') ;} Console.log (result);
Bluebird-core API (i)