JavaScript encapsulates asynchronous functions - [Asynchronous programming] - How to get the result of an asynchronous operation in a function?

       Have we encountered such a situation when writing a project: in a function, another asynchronous function is nested, so how to obtain the result of this asynchronous function outside? (return value)
       For example, such an example:

function fn() {
    
    
	setTimeout(function(){
    
    
		let data = 222
	},2000)
}

How do we get the value of data in the timer?


Method 1 passes in the callback function

function fn(callback) {
    
    
	setTimeout(function(){
    
    
		let data = 222
		callback(data)
	},2000)
}

fn(function(data){
    
    
	console.log(data)	//	222
})

We cleverly pass in a callback function in fn, call this callback function in the timer function, and bring out the result in the timer function in the form of function parameters , so that we can get the result through the callback of fn !
In fact, such an operation is also called - encapsulating asynchronous API (encapsulating asynchronous functions).
We encapsulate the timer asynchronous function through the fn function.

Method 2 Promise

function fn() {
    
    
	return new Promise(function (resolve, reject) {
    
    
            	setTimeout(function () {
    
    
                	let data = 222
                	resolve(data)
            	}, 2000)
        	})
}
    
fn().then(function(data) {
    
    
	console.log(data)
})

Use Promise to wrap the asynchronous function, when calling fn, it will return a Promise instance, call the then function of the Promise instance, and we can get the successful callback value.

Guess you like

Origin blog.csdn.net/weixin_60297362/article/details/123129825