Examples of Promise asynchronous programming
// 1. solve the asynchronous callback problem // 1.1 how to synchronize asynchronous requests // if there are no pre-and post-order differences between several asynchronous operations, the subsequent tasks can be executed only after multiple asynchronous operations are completed, const fs = require ('fs'); let school ={}; fs. readFile ('. /name.txt ', 'utf8', function (err, data) {school. name = data;}); fs. readFile ('. /age.txt ', 'utf8', function (err, data) {school. age = data ;}); console. log (school); // 1.2 How to Solve callback hell // when multiple operations are required, multiple callback functions are nested, resulting in less intuitive code, it is often said that the callback hell const fs = require ('fs'); fs. readFile ('. /content. tx T', 'utf8', function (err, data) {if (err) console. log (err); fs. readFile (data, 'utf8', function (err, data) {if (err) console. log (err); console. log (data) ;})}); // 2. promise // the intention of Promise is to Promise that I will give you a result after a while. When will it take a while? The answer is asynchronous operations. asynchronous operations are performed only after a long period of time, such as network requests and local file reading. // 3. promise three States // For example, if my daughter-in-law says he wants to buy a package, then he will "wait" for my reply. I can buy it in two days. If yes, it means "successful ", if I refuse, it indicates "failed ", of course, I may keep dragging for a lifetime. // The initial status of the Pending Promise object instance when it is created. // Fulfilled can be understood as a successful status. // Rejected can be understood as a failed status. // then the method is used to specify the operations to be executed when the state of the Promise object changes, the first function (onFulfilled) is executed during resolve, and the second function (onRejected) is executed during reject. // 4. construct a Promise // 4.1 promise method and immediately execute let promise = new Promise () => {console. log ('hello') ;}); console. Log ('World'); // 4.2 promise can also represent a future value const fs = require ('fs'); let promise = new Promise (resolve, reject) ==>{ fs. readFile ('. /content.txt ', 'utf8', function (err, data) {if (err) console. log (err); resolve (data) ;}}); promise. then (data => {console. log (data) ;}); // 4.3 represents a value for not returning const fs = require ('fs'); let promise = new Promise (resolve, reject) =={}); promise. then (data => {console. log (data) ;}); // 4.4 Application Status throw Coin function flip_coin () {return new Promise (resolve, reject) =>{ setTimeout (function () {var random = Math. random (); if (random> 0.5) {resolve ('position') ;}, 2000)} flip_coin (). then (data => {console. log (data) ;}, data =>{ console. log (data) ;}); // 5. implement simple Promisefunction Promise (fn) {fn (data) => {this. resolve (data)}, (data) => {this. reject (data) ;}} Promise. prototype. resolve = function (Data) {this. _ success (data)}; Promise. prototype. reject = function (data) {this. _ error (data) ;}; Promise. prototype. then = function (success, error) {this. _ success = success; this. _ error = error;}; // 6. error will trigger Reject // The second parameter of then can be used to capture the failure, or the catch function can be used to capture function flip_coin () {return new Promise (resolve, reject) =>{ throw Error ('no coin ')} flip_coin (). then (data => {console. log (data );}). catch (e) => {conso Le. log (e) ;}) // 7. promise. all implements parallel processing // accepts an array. all instances in the array are Promise instances, and a Promise instance is returned. The status transfer of this Promise instance depends on the status change of the parameter Promise instance. When all instances in the resolve status are in the Promise status, the returned Promise instance changes to the resolve status. If any instance in the parameter is in the reject state, the returned Promise instance changes to the reject State const fs = require ('fs'); let p1 = new Promise (resolve, reject) ==>{ fs. readFile ('. /name.txt ', 'utf8', function (err, data) {resolve (data) ;}) let p2 = new Promise (resolve, reject) ==>{ fs. redFile ('. /age.txt ', 'utf8', function (err, data) {resolve (data) ;}) Promise. all ([p1, p2]). then ([res1, res2]) => {console. log (res1);}) // No matter who completes the two promise, Promise. the all method follows Returns results in sequence. // 8. promise. the race implementation selects to accept an array, which contains all Promise instances and returns a Promise instance. The status transfer of this Promise instance depends on the status change of the Promise instance of the parameter. When any instance in the parameter is in the resolve state, the returned Promise instance changes to the resolve state. If any instance in the parameter is in the reject state, the returned Promise instance changes to the reject state. Const fs = require ('fs'); let p1 = new Promise (resolve, reject) => {fs. readFile ('. /name.txt ', 'utf8', function (err, data) {resolve (data) ;}) let p2 = new Promise (resolve, reject) ==>{ fs. readFile ('. /age.txt ', 'utf8', function (err, data) {resolve (data) ;}) Promise. race ([p1, p2]). then ([res1, res2]) => {console. log (res1, res2) ;}) 9. promise. resolve // returns a Promise instance, which is in the resolve state. Promise. resolve ('success '). then (data => {console. log (data) ;}) 10. promise. reject // return a Promise instance, which is in the reject state. reject ('failed '). then (data => {console. log (data) ;}, re =>{ console. log (re);}) // 11. encapsulate ajaxfunction ajax ({url = new Error ('url must provide '), method = 'get', async = true, dataType = 'json '}) {return new Promise (function (resolve, reject) {var xhr = new XMLHttpRequest (); xhr. open (method, url, async); xhr. responseType = dataType; xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (/^ 2 \ d {2 }/. test (xhr. status) {resolve (xhr. response);} else {reject (xhr. response) ;}} xhr. send () ;}) ;}// 12. promise. resolve ([1, 2, 3]). then (arr => {return [... arr, 4]}). then (arr => {return [... arr, 5]}). then (arr => {console. log (arr);}) // 13. the result returned by promise // then in the chain is the result of promise's resolve. Promise. resolve ('user '). then (data => {return new Promise (function (resolve, reject) {fetch ('/' + data ). then (res => res. json (). then (json) =>{ resolve (json )}))})}). then (data => {console. log (data) ;}); // easier to rewrite Promise. resolve ('user '). then (data =>{ return fetch ('/' + data )}). then (res => {return res. json ();}). then (data => {console. log (data) ;}) // 14. async/await // The essence is syntactic sugar. await and async must be used together. After await, it can only be used with promise async function getHello () {return new Promise (resolve, reject) ==>{ setTimeout (function () {resolve ('hello') ;}, 2000) ;}} async function getData () {var result = await getHello (); console. log (result) ;}; getData ();