Javascript uses the Promise object for asynchronous programming. javascriptpromise
The Promise object is the unified interface provided by the CommonJS Working Group for asynchronous programming. It is the native support for Promise in ECMAScript6, and Promise is what will happen in the future, using Promise can avoid layer-by-layer nesting of callback functions, and it also provides a standard for easier control of asynchronous operations. Provides reject, resolve, then, and catch methods.
Use PROMISE
Promise is a native object after ES6. You 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 function (resolve, reject) is defined here. If the call succeeds, resolve is called. If the call fails, reject is called.
Promise. prototype. then is the callback after Promise is executed. You can use the then method to specify the resolve and reject callbacks respectively.
promise.then(function () { console.log(' resolve from promise');}, function () { console.log(' reject from promise');});
Result 1:
begin do something run success resolve from promise
Result 2:
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 for network requests, or use Promise to implement Ajax requests on browsing.
Address: https://github.com/jjz/node
Articles you may be interested in:
- Six features of the Promise mode in JavaScript asynchronous programming
- Detailed introduction to asynchronous programming specification Promises/A in Javascript
- Use q. js in node. js to implement api promise
- Use Promise in NodeJS to encapsulate asynchronous Functions
- Example: How to Use Promise in JavaScript