Send native Ajax request based on Promise
// Send native Ajax request based on Promise function queryData(url) { //resolve successful callback function reject failed callback function var p = new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState != 4) return; if(xhr.readyState == 4 && xhr.status == 200) { // Deal with normal conditions resolve(xhr.responseText); }else{ // Handling exceptions reject('Server error'); } }; xhr.open('get', url); xhr.send(null); }); return p; } // Send multiple ajax requests and ensure the order queryData('http://localhost:3000/data') .then(function(data){ console.log(data) return queryData('http://localhost:3000/data1'); }) //Here, then points to the promise object of the return above .then(function(data){ console.log(data); return 'hello'; }) //Here, then points to the newly created promise object returned by return above .then(function(data){ console.log(data) });
Asynchronous task API
. then(function(data) {}) function successfully executed
. catch(function(error) {}) function executed in error
. finally(function() {}) a function that will execute regardless of success or failure
The. race([a,b,..]) parameter is an array, and the array is a promise object. This method executes all asynchronous functions in the array, and returns the result of a promise object executed as soon as possible
. all ([a,b,..]) parameter is an array, and the array is a promise object. This method needs all asynchronous functions to execute before returning results
var p1 = queryData('http://localhost:3000/a1'); var p2 = queryData('http://localhost:3000/a2'); var p3 = queryData('http://localhost:3000/a3'); Promise.all([p1,p2,p3]).then(function(result){ console.log(result) }) Promise.race([p1,p2,p3]).then(function(result){ console.log(result) })
Fetch (similar to promise)
Fetch API is a new ajax solution
The Fetch will return Promise fetch, which is not a further encapsulation of ajax, but a native js without using the XMLHttpRequest object
//Using Express framework to build server const express = require('express') const app = express() // The Express framework uses body parser as the request body parsing middleware by default const bodyParser = require('body-parser') // Processing static resources app.use(express.static('public')) // Processing parameters app.use(bodyParser.json()); // false means to use the system module querystring for processing, which is also officially recommended. true means to use the third-party module app.use(bodyParser.urlencoded({ extended: false })); // Set to allow cross domain access to the service app.all('*', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Headers', 'mytoken'); next(); }); //Server get request interface 1 app.get('/fdata', (req, res) => { res.send('Hello Fetch!') }) /* //Client request code fetch('http://localhost:3000/fdata').then(function(data){ // text()Method is part of the fetchAPI, which returns a Promise instance object to retrieve the data returned in the background return data.text(); }).then(function(data){ console.log(data); }) */ //Server side get request interface 2 app.get('/books', (req, res) => { // Query is the query parameter of url res.send('Conventional URL Transfer parameters!' + req.query.id) }) /* //Client request code //GET Parameter passing - traditional URL fetch('http://localhost:3000/books?id=123', { method: 'get' }) .then(function(data){ //Convert return value to string return data.text(); }).then(function(data){ // Output 123 console.log(data) }); */ //Server get request interface 3 app.get('/books/:id', (req, res) => { // params is the parameter name res.send('Restful Formal URL Transfer parameters!' + req.params.id) }) /* //Client request code //GET Parameter passing - URL in restful form fetch('http://localhost:3000/books/456', { method: 'get' }) .then(function(data){ return data.text(); }).then(function(data){ console.log(data) }); */ //Server side delete request interface app.delete('/books/:id', (req, res) => { res.send('DELETE Request delivery parameters!' + req.params.id) }) /* //Client request code //DELETE Request mode parameter passing fetch('http://localhost:3000/books/789', { method: 'delete' }) .then(function(data){ return data.text(); }).then(function(data){ console.log(data) }); */ //Server side post request interface I app.post('/books', (req, res) => { //The body here is processed by parsing Middleware res.send('POST Request delivery parameters!' + req.body.uname + '---' + req.body.pwd) }) /* //Client request code //POST Request dissemination fetch('http://localhost:3000/books', { method: 'post', body: 'uname=lisi&pwd=123', headers: { //Here, make sure to set the type type to: 'uname = Lisi & PWD = 123' format 'Content-Type': 'application/x-www-form-urlencoded' } }) .then(function(data){ return data.text(); }).then(function(data){ console.log(data) }); */ //Server side post request interface II app.put('/books/:id', (req, res) => { res.send('PUT Request delivery parameters!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd) }) /* //Client request code //POST Request dissemination fetch('http://localhost:3000/books', { method: 'post', body: JSON.stringify({ uname: 'Zhang three ', pwd: '456' }), headers: { //The parameter type set here is json format 'Content-Type': 'application/json' } }) .then(function(data){ return data.text(); }).then(function(data){ console.log(data) }); */ //Server put request interface app.put('/books/:id', (req, res) => { res.send('PUT Request delivery parameters!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd) }) /* //Client request code // PUT Request dissemination fetch('http://localhost:3000/books/123', { method: 'put', body: JSON.stringify({ uname: 'Zhang three ', pwd: '789' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data){ return data.text(); }).then(function(data){ console.log(data) }); */