The Promise object is a unified interface provided by the CommonJS working group for asynchronous programming. It is the native support for Promise provided in ECMAScript6. Promise is what will happen in the future. Using Promise can avoid layers of nesting of callback functions and also provides The specification makes it easier to control asynchronous operations. Provides methods such as reject, resolve, then and catch.
Use PROMISE
Promise is a native object after ES6. We only need to instantiate the Promise object to 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(); } });
A callback method function(resolve,reject) is defined here. If it succeeds, resolve will be called. If it fails, reject will be called.
Promise.prototype.then is the callback after Promise is executed. You can use the then method to specify the callbacks of resolve and reject respectively.
promise.then(function () { console.log(' resolve from promise'); }, function () { console.log(' reject from promise'); });
Execution result one:
begin do something run success resolve from promise
Execution result two:
begin do something run failed reject from promise
Use PROMISE for network requests
getRequest = function (url) { var promise = new Promise(function (resolve, reject) { var request = require('request'); request(url, function (error, respones, body) { if (error) { reject(error); return; } if (respones.statusCode == 200) { 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 to make network requests, and you can also use Promise to implement Ajax requests on browsing.
Code address: https://github.com/jjz/node