Promise object definitions:
For handling asynchronous programming
Features Promise objects
- State of the object from external influences
- Once the status change, it will not change any time can get this result
Promise state object
pending
(processing)fulfilled
(succeeded)rejected
(Failed)
Promise to change the state of the object two possible
- From
pending
becomefulfilled
- From
pending
becomerejected
Promise shortcomings object
- Can not be canceled
Promise
, it will be executed immediately once the new can not be canceled during; - If you do not set a callback function,
Promise
internal error thrown, it does not react to the outside; - When in the
pending
state, progress is currently no way of knowing where a stage (beginning or nearing completion).
Basic usage Promise
- ES6 predetermined,
Promise
the object is a constructor to generatePromise
instances. Promise
Constructor parameter is a function , the function of the two parameters, respectivelyresolve
andreject
. They are two functions provided by the JavaScript engine, do not have to deployresolve
Function returns thePromise
object's state from "not completed" to "success" (i.e., changed from pending resolved), the call is successful asynchronous operation , and the result of the asynchronous operation, to pass out as a parameterreject
Function returns thePromise
object's state from "not completed" to "failed" (i.e., changed from pending Rejected), the asynchronous operation failed calls, and asynchronous operation errors may be, as a parameter to pass out-
const promise = new Promise(function(resolve, reject) { // ... some code if (/* 异步操作成功 */){ resolve(value); } else { reject(error); } });
Bythen
the method are designatedresolved
state and arejected
callback status . Promise
After the instance generation, you canthen
specify methodsresolved
state and arejected
callback status.then
The method can accept two callback functions as arguments.
1. The first callback function isPromise
the state becomes the objectresolved
invocation,
2. The second is the callbackPromise
object's state changesrejected
invoked.
3. Among them, the second function is optional and not required to provide. Both functions accept thePromise
value of the object as a parameter spread.-
function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(resolve, ms, 'done'); }); } timeout(100).then((value) => { console.log(value); });
In the above code,
timeout
the method returns anPromise
instance, shows the result after a period of time will occur.
After a specified time (ms
parameter) after thePromise
state of the instance becomesresolved
, it will triggerthen
callback method binding.
New Promise will be executed immediately after. -
let promise = new Promise(function(resolve, reject) { console.log('Promise'); resolve(); }); promise.then(function() { console.log('resolved.'); }); console.log('Hi!'); // Promise // Hi! // resolved
In the above code, Promise performed immediately after the new, the first output is
Promise
.
Then,then
the method specified callback function, the script will be executed in the current sync all tasks executed, soresolved
the final output.
Pictures lazy loading
-
function loadImageAsync(url) { return new Promise(function(resolve, reject) { const image = new Image(); image.onload = function() { resolve(image); }; image.onerror = function() { reject(new Error('Could not load image at ' + url)); }; image.src = url; }); }
resolve
Function and reject
parameter function problems
reject
Function parameters are usually Error
instances of an object representing error thrown; resolve
function parameters other than the normal value, but also may be another example of Promise
- With the
Promise
object implements Ajax operations
const getJSON = function(url) { const promise = new Promise(function(resolve, reject){ const handler = function() { if (this.readyState !== 4) { return; } if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); } }; const client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send(); }); return promise; }; getJSON("/posts.json").then(function(json) { console.log('Contents: ' + json); }, function(error) { console.error('出错了', error); });
The above code,
getJSON
is the encapsulation of the XMLHttpRequest object, for issuing a request for HTTP JSON data, and returns anPromise
object.
Note that, in thegetJSON
interior,resolve
the function andreject
the function is called, it has parameters.If you call
resolve
the function andreject
with a parameter to a function, then their argument will be passed to the callback function.reject
Function parameters are usuallyError
instances of an object representing error thrown;resolve
function parameters other than the normal value, but also may be another example of Promise, such like this. resolve
It is a parameter of the function instance Promiseconst p1 = new Promise(function (resolve, reject) { setTimeout(() => reject(new Error('fail')), 3000) }) const p2 = new Promise(function (resolve, reject) { setTimeout(() => resolve(p1), 1000) }) p2 .then(result => console.log(result)) .catch(error => console.log(error)) // Error: fail
The above code,
p1
a Promise, becomes 3 seconds laterrejected
.p2
One second after the state change,resolve
the method returnsp1
.
Becausep2
the return is another Promise, leading top2
their own state invalidated by thep1
state decisionp2
states.
So, behind thethen
statements have become for the latter (p1
).
It took another two seconds,p1
turnsrejected
, leading the triggercatch
method specified callback function.resolve
Orreject
does not perform the function parameters of the end of Promise-
new Promise((resolve, reject) => { resolve(1); console.log(2); }).then(r => { console.log(r); }); // 2 // 1
The above code calls
resolve(1)
later, the latterconsole.log(2)
would be executed and will be printed first.
This is because the Promise is resolved immediately at the end of the current round of the event loop execution, always in sync task late round cycle.In general, calling
resolve
orreject
later, Promise mission is complete, subsequent operations should be placedthen
inside the method, and should not be written directly onresolve
orreject
behind.
Therefore, the best in front of them plus thereturn
statements, so there would be no accident.
In general, callingresolve
orreject
later, Promise mission is complete, subsequent operations should be placedthen
inside the method, and should not be written directly onresolve
orreject
behind.
Therefore, the best in front of them plus thereturn
statements, so there would be no accident. -
new new Promise ((Resolve, Reject) => { return Resolve (. 1 ); // the latter statement will not execute the console.log (2 ); })
Promise.prototype.then()
Promise instance has then
methods, i.e., then
methods in the prototype object is defined Promise.prototype
on.
Its role is to add callback function for the state change Promise instance.
As mentioned above, then
the first argument of the method is resolved
a callback function of the state, and the second parameter (optional) is the rejected
callback status.
then
Method returns a new Promise
instance (note, not the original Promise
instance). It can be written using the chain, i.e. then
after the method then calls another then
method.
getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // ... });
Promise.prototype.catch()
Promise.prototype.catch
Method .then(null, rejection)
or .then(undefined, rejection)
alias for the specified callback function an error occurs.
getJSON ( '/ posts.json'). the then ( function (Posts) { // ... }). the catch ( function (error) { // an error occurred while processing a previous callback getJSON and run console.log ( 'error occurs!' , error); });
The above code, the getJSON
method returns a Promise object, if the state of the object changes resolved
, it will call the then
method specified callback function;
If the asynchronous operation throws an error, status changes rejected
, will call the catch
method specified callback function, to deal with this error.
In addition, the then
method specified callback function, if the operation throws an error, will be catch
capture method.
Promise.prototype.finally()
finally
Regardless of the method used to target Promise final state, the operation will be performed specified. The standard method is introduced ES2018.
promise .then(result => {···}) .catch(error => {···}) .finally(() => {···});
In the above code, regardless of promise
the final status after executing then
or catch
after the specified callback function that executes finally
the method specified callback function.
Promse.all()
Promise.all
A method for multiple instances Promise, Promise packaged into a new instance.
const p = Promise.all([p1, p2, p3]);
The above code, the Promise.all
method takes an array as a parameter, p1
, p2
, p3
are examples Promise, if not, the following will be called first mentioned Promise.resolve
method, the parameter into Promise instance, further processing. ( Promise.all
Method parameters may not be an array, but must have the Iterator interface, and each member is returned Promise instance.)
p
State by the p1
, p2
, p3
determined, is divided into two cases.
(1) Only p1
, p2
, p3
is turned into a state fulfilled
, p
the state will become a fulfilled
this case p1
, p2
, p3
the return value consisting of an array, is passed to the p
callback function.
(2) long p1
, p2
, p3
being there is to be a rejected
, p
a state becomes rejected
, the first case is reject
the return value of the instance, is passed to the p
callback function.
Promise.race()
Promise.race
The method also multiple instances Promise, Promise packaged into a new instance.
const p = Promise.race([p1, p2, p3]);
In the above code, as long as p1
, p2
, p3
in one instance first to change state, p
the state will change accordingly. Promise to return the value of that instance of the first to change, it is passed to the p
callback function.
Promise.race
Parameters and methods Promise.all
the same way, if not Promise instance, it will first call the below mentioned Promise.resolve
method, the parameters into Promise instance, further processing.
Here is an example, if the result is not obtained within the specified time, the state will be changed Promise reject
otherwise becomes resolve
.
Promise.resolve()
Sometimes you need to turn existing objects Promise objects, Promise.resolve
methods to play this role.
const jsPromise = Promise.resolve($.ajax('/whatever.json'));
Surface jQuery code generated deferred
object into a new Promise object.
Promise.resolve
Equivalent to the following wording.
Promise.resolve('foo') // 等价于 new Promise(resolve => resolve('foo'))
Promise.resolve
Method parameters into four cases.
(1) is a parameter instance Promise
If the argument is Promise instance, it Promise.resolve
will not do any modification, is returned unchanged this instance.
(2) the parameter is a thenable
target
thenable
It refers to an object having then
an object method, the object such as the following.
let thenable = { then: function(resolve, reject) { resolve(42); } }; let p1 = Promise.resolve(thenable); p1.then(function(value) { console.log(value); // 42 });
Promise.resolve
This method will be converted to objects Promise objects, then immediately execute thenable
object then
methods.
The above code, thenable
object then
after performing the method, the object p1
state becomes resolved
, so that immediately after the last execution then
method specified callback function, the output 42.
(3) has a parameter is not then
an object method, or is simply not an object
If the parameter value is an original or not having an then
object method, the Promise.resolve
method returns Promise a new object state resolved
.
const p = Promise.resolve('Hello'); p.then(function (s){ console.log(s) }); // Hello
The above example of a new code generation Promise object p
.
Because the string Hello
does not belong to asynchronous operation (determination method is then subject does not have a string method), and returns from a state Promise instance is generated resolved
,
Therefore, the callback function will be executed immediately. Promise.resolve
Method parameters, simultaneously passed to the callback function.
(4) no parameters
Promise.resolve()
With no parameters method allows the caller directly returns a resolved
Promise object's state.
So, if you want to get a Promise objects, more convenient way is to directly call the Promise.resolve()
method.
const p = Promise.resolve(); p.then(function () { // ... });
Variable code above p
is a Promise object.
It should be noted that immediately resolve()
the Promise object is executed at the end of the current round of "event loop" (event loop), rather than when the next round start "event loop".
setTimeout(function () { console.log('three'); }, 0); Promise.resolve().then(function () { console.log('two'); }); console.log('one'); // one // two // three
The above code, setTimeout(fn, 0)
the next round "event loop" started when, Promise.resolve()
executed when the current round of "event loop" end, console.log('one')
it is immediately executed, and therefore the first output.
Promise.reject()
Promise.reject(reason)
The method also returns a new Promise instance, the state of the instance rejected
.
const p = Promise.reject ( 'wrong' ); // equivalent to const = P new new Promise ((Resolve, Reject) => Reject ( 'wrong' )) p.then ( null , function (S) { Console .log (S) }); // wrong
The above code creates an instance of the object Promise p
, state rejected
, the callback function is executed immediately.
Note that the Promise.reject()
parameters of the method, as will be intact reject
reason, the parameters into a subsequent process. This point is Promise.resolve
inconsistent methods.
onst thenable = { then(resolve, reject) { reject('出错了'); } }; Promise.reject(thenable) .catch(e => { console.log(e === thenable) }) // true
The above code, the Promise.reject
method parameter is a thenable
target, after the execution, the back catch
parameter method is not reject
out of the "wrong" string, but thenable
the object.
application
- Load picture
const preloadImage = function (path) { return new Promise(function (resolve, reject) { const image = new Image(); image.onload = resolve; image.onerror = reject; image.src = path; }); };
-
Generator function of binding with Promise
function getFoo () { return new Promise(function (resolve, reject){ resolve('foo'); }); } const g = function* () { try { const foo = yield getFoo(); console.log(foo); } catch (e) { console.log(e); } }; function run (generator) { const 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 go(it.throw(error)); }); } go(it.next()); } run(g);
Generator functions above code
g
in, there is an asynchronous operationgetFoo
, it returns is aPromise
target. Functionrun
to handle thePromise
object and call the nextnext
method.
Relevant information: