The Promise object is a unified interface provided by the COMMONJS workgroup for asynchronous programming, which provides native support for promise in ECMASCRIPT6, and promise is what happens in the future, and using promise avoids the layer nesting of callback functions, It also provides the specification for easier control of asynchronous operations. Provides methods such as Reject,resolve,then and catch.
Using Promise
Promise is the native object after ES6, we just need to instantiate the Promise object and use it directly.
Instantiate promise:
var promise = new Promise (function (resolve, reject) {
console.log (' Begin do something ');
if (Math.random () * 10.0 > 5) {
Console.log ("Run Success");
Resolve ();
} else {
Console.log ("Run Failed");
Reject ();
}
);
This defines a callback method function (Resolve,reject) that, if successful, calls resolve, and the reject is invoked if it fails.
Promise.prototype.then is a callback after Promise is executed, you can specify resolve and reject callbacks separately using the then method.
Promise.then (function () {
Console.log (' Resolve from promise ');
}, Function () {
console.log (' Reject From promise ');
Implementation results One:
Begin do something
run success
resolve from Promise
Implementation Result II:
Begin do something
run failed
reject from promise
Using Promise for network requests
getrequest = function (URL) {
var promise = new Promise (function (resolve, reject) {
var request = require (' Reque St ');
Request (URL, function (error, respones, body) {
if (error) {
reject (error);
return;
}
if (Respones.statuscode = =) {
Resolve (body)
} else {
reject (respones.status);
}
}); return
promise;
};
Getrequest ("https://github.com/"). Then (function (Result) {
console.log (result);
}, Function (Error) {
console.error (' Error ', error);
};
Use promise for network requests, or you can use promise to implement AJAX requests on browsing.
Code Address: Https://github.com/jjz/node