Promise introduction
Promise is a constructor and a solution for asynchronous programming. The so-called Promse itself is a container that holds the results of asynchronous operations. Yes, it is similar to a callback function.
The Promise container itself is not asynchronous, but encapsulates an asynchronous task. He has three states: 1. Pending, 2. Resolved, and 3. Rejected. The state can only be one.
Promise get file information
const fs = require('fs'); let p1 = new Promise((resolve, reject) => { fs.readFile('./data/a.txt', 'utf8', (error, data) => { if (error) { reject(error); } else { resolve(data); } }); }); let p2 = new Promise((resolve, reject) => { fs.readFile('./data/b.txt', 'utf8', (error, data) => { if (error) { reject(error); } else { resolve(data); } }); }); let p3 = new Promise((resolve, reject) => { fs.readFile('./data/c.txt', 'utf8', (error, data) => { if (error) { reject(error); } else { resolve(data); } }); }); // then Chain programming of p1 .then(data => { console.log('a Data', data); // When p1 When the reading is successful // In the current function return The result is the following then in Function Receive // When you return 123 We'll get 123 later. // No, return,What we're going to receive is undefined // Those above return Data is not very soft. // What really works, return One Promise object // When return One Promise Object, subsequent then The first parameter of the method in will be the result of this object return p2; }, error => { console.log('read file a failed', error); }) .then(data => { console.log('b Data', data); return p3; }, error => { console.log('read file b failed', error); }) .then(data => { console.log('c Data', data); }, error => { console.log('read file c failed', error); })
Obviously, the above example is particularly troublesome!
Choose, let's encapsulate Promise
const fs = require('fs'); const pReadFile = (filePath) => { return new Promise((resolve, reject) => { fs.readFile(filePath, 'utf8', (error, data) => { if (error) { reject(error); } else { resolve(data); } }); }); }; pReadFile('./data/a.txt') .then(data => { console.log('a file data: ', data); return pReadFile('./data/b.txt'); }) .then(data => { console.log('b file data: ', data); return pReadFile('./data/c.txt'); }) .then(data => { console.log('c file data: ', data); });
Promise cooperates with AJAX to obtain information
data.json file:
{ "users": [ { "id": 1, "username": "admin-1", "age": 18, "job": 2 }, { "id": 2, "username": "admin-2", "age": 18, "job": 4 }, { "id": 3, "username": "admin-3", "age": 18, "job": 5 } ], "jobs": [ { "id": 1, "name": "Student" }, { "id": 2, "name": "Teacher" }, { "id": 3, "name": "Driver" }, { "id": 4, "name": "performer" }, { "id": 5, "name": "Engineer" }, { "id": 6, "name": "Programmer" } ] }
Code:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <title>Solo show doesn't love show</title> </head> <body> <form id="user-form"></form> <script type="text/html" id="tpl"> <div> <label for="">User name</label> <input type="text" value="{{ user.username }}"> </div> <div> <label for="">Age</label> <input type="number" value="{{ user.age }}"> </div> <div> <label for="">Occupation</label> <select name="" id=""> {{ each jobs }} {{ if user.job === $value.id }} <option value="{{ $value.id }}" selected>{{ $value.name}}</option> {{ else }} <option value="{{ $value.id }}">{{ $value.name}}</option> {{ /if }} {{ /each }} </select> </div> </script> <script src="node_modules/art-template/lib/template-web.js"></script> <script src="node_modules/jquery/dist/jquery.js"></script> <script type="text/javascript"> /** * It can achieve callback acquisition * It can also be obtained by. then method. */ const pGet = (url, callback) => { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onload = () => { resolve(JSON.parse(xhr.responseText)); callback && callback(JSON.parse(xhr.responseText)); } xhr.onerror = (error) => reject(error); xhr.open('get', url); xhr.send(); }); }; let currentData = {}; pGet('./data.json') .then((data) => { currentData.user = data.users[0]; return data.jobs; }) .then((jobsData) => { currentData.jobs = jobsData; let htmlStr = template('tpl', currentData); document.getElementById('user-form').innerHTML = htmlStr; }); </script> </body> </html>