promise

  • Promise is a constructor
  • Promise.prototype has. Then and. Catch methods
  • Promise denotes an asynchronous operation

Const p = new Promise() means you created a formal asynchronous operation because you don’t know what the actual asynchronous operation is.

The specific asynchronous operations are written in the Promise (function () {}). For example, reading a file is an asynchronous operation

 	const p = new Promise(function(){
        fs.readFile('File 1 path'.' utf-8 '.function(err , data){
            if(err){
                console.log(err.message)
            }
            else{
                console.log(data)
            }
        })
    })
Copy the code

As we all know, the final results returned by asynchronous operations are in no fixed order

	const p = new Promise(function(){ fs.readFile('File 1 path'), 'utf-8'.function(){...} }) // File 1 contains 111
	
	const p2 = new Promise(function(){ fs.readFile('File 2 path'), 'utf-8'.function(){...} }) // File 2 contains 222

	const p3 = new Promise(function(){ fs.readFile('File 3 path'), 'utf-8'.function(){...} }) // File 3 says 333
Copy the code

As in the above code, the output may not be 111-222-333, but it may be 111-333-222, and so on. Because reading files is an asynchronous operation

What if I want the results of some asynchronous operations to be executed in a certain order? For example, return the file contents in 111-222-333

const p = new Promise(function(){
	fs.readFile('File 1 path'', ,function(err, data){ if (err) {} else{ console.log(data); fs.readFile('file2The path' '.function(err,data){
			if (err) {}
        	else{
            	console.log(data);
				fs.readFile('File 3 path'',,function(err,data){... }}})}})Copy the code

The second file can be read in the callback function after the first file has been read successfully and the third file can be read in the callback function after the second file has been read successfully. This will read 111-222-333 in order

But with so many functions nested in such a large piece of code, it was unsightly and difficult to maintain, and I suddenly wanted to change the order of the file contents and rearrange large chunks of code.

So what to do?

. And then. The catch


In the Promise function, successCallback and errorCallback are two parameters: successCallback and errorCallback

 	const p = new Promise(function (successCallback, errorCallback){
 		fs.readFile('File path'.'utf-8'.function(err,data){
            if(err){
                errorCallback(err.message)
            }
            else{
				successCallback(data)
            }
        })
 	})
Copy the code

The Promise object has.then and.catch methods that define the contents of the successCallback and errorCallback callback callback functions

  • Then (function(){}, function(){}) corresponds to successCallback, errorCallback
  • Catch (function(){}) corresponds to errorCallback

Let’s wrap this asynchronous file-reading operation into a function for easy call

function getContentFile( fpath ){
	const p = new Promise(function(successCallback, errorCallback){
     	fs.readFile(fpath,'utf-8'.function(err,data){
            if(err){
                successCallback(err.message)
            }
            else{
                errorCallback(data)
            }
    	})   
    })

}
Copy the code

We need the getContentFile() function to return a Promise object before we can use the.then and.catch methods. So we return new Promise()

	function getContentFlie( fpath ){
		return new Promise(function(successCallback, errorCallback){...})
                                                             	}
Copy the code

Call the getContentFile function

var p = getContentFile('File 1 path') // Returns a Promise object
p.then(function(data){
	console.log(data)
	return getContentFile('File 2 path') // Returns a Promise object so that you can continue calling the then method
}).then(function (data){
    console.log(data)
    return getContentFile('File 3 path') 
}).then(function (data){
    console.log(data)
}).catch(function (err) {
    console.log(err.message)
})// Finally add a catch method at the end to define the contents of the failure callback
Copy the code

This is much cleaner than the previous callback code but only relative to the previous code.

But I still think it’s ugly and difficult to maintain how do you say?

Async and await


This is where await and async come in, which are modifiers. Use them to simplify the. Then operation directly. Can be used directly in.then

Await can only be used in methods decorated with async

If the return value of a method is a Promise instance object, then the Promise instance can be decorated with the await keyword

Remove the asynchronous read file operations encapsulated above

// Return the Promise object
function getContextFile (fpath){
	return new Promise(function (successCallback, errorCallback){
	 	fs.readFile(fpath,'utf-8'.function (err, data){
	 		if (err) {  return errorCallback(err.message); }
	 		else{ returnsuccessCallback(data); }})})}//await decorates asynchronous operations, async decorates methods that contain await decorates asynchronous operations
async function test(){
        const data1 = await getContextFile('File 1 path')
        // getContextFile is decorated so that data1 gets the contents of file 1 successfully read, without setting the callback function in data1.then
        console.log(data1) 
}

test()
Copy the code

Call the test function to output the contents of file 1

Of course, what if there is a read failure. Just add the catch method to the end

async function test(){
        const data1 = await getContextFile('File 1 path').catch(function (err){return err})
        if(data1 instanceof Error) {console.log('File reading failed')}else{        
        	console.log(data) 
        }
}
Copy the code

In order, just call getContextFile several times in order from the test function

async function test(){
        const data1 = await getContextFile('File 1 path')...console.log(data1)
        
        const data2 = await getContextFile('File 2 path')...console.log(data2)
    
        const data2 = await getContextFile('File 3 path')...console.log(data3)
}

test() // Result 111 222 333 is displayed
Copy the code

Asynchronous operations cannot be output sequentially. This makes asynchronous operations output sequentially just like non-asynchronous operations.

axios

Axios is used to make AJAX requests. Making AJAX requests is also asynchronous. Axios. get and axios.post return promise objects

Getinfo(){
	const result = axios.get('http://www.liulongbin.top:3005/api/get')
    
    
	result.then(function(res){
        console.log(res)
    })
}

		// This is too cumbersome to write. Get returns a promise object and we can await it. If we await an asynchronous operation, we should await it with async.
		// All we need is a data attribute in the requested object. The promise object that is requested back using AXIos comes with six properties.
		// Finally we want to get the data in the data attribute (free data attribute). You can use deconstruction assignment
		/ / such as
		// car{
		// name:' audi ',
		// number:1111
		// }
		// const { name, number } = car
		// console.log(name); // Output audi
		// Give a separate name to your name
		// const { name: carname ,number}
async	Getinfo(){
	const { data:res }	 = await axios.get('interface')

	console.log(res.data);
}
Copy the code