Promise and callback function that you can understand


Callback function (callback)

What is a callback function?

A function that is passed into another function as an actual parameter and called within the external function, used to complete certain tasks, is called a callback function

That is a callback function, as 参数another JavaScript function passed to the callback function will be executed immediately after the function execution is complete. The callback function is called and executed inside the passed function.
Examples

// 回调函数
function callback(param) {
    console.log('I am callback! param: ',param)
}
// 函数
function myFunc(param, callback) {
	setTimeout(()=>{
		callback(param) //执行回调函数
	},2000)
}

myFunc(1, callback) //等待2秒后:I am callback! param: 1

Why use callbacks

The example
executes the function immediately: the following two functions are executed immediately and can return the result correctly

function getInfo() {
    return 'I am Ryan'
}
function showInfo(param) {
    console.log(param)
}

showInfo(getInfo()) // I am Ryan

But if you getInfoneed to request access to the network, it will no longer be able to get the correct result

function getInfo() {
	// 延时模拟网络请求
	setTimeout(()=>{
		return 'I am Ryan'
	},2000)
}
function showInfo(param) {
    console.log(param)
}

showInfo(getInfo()) // undefined

This time the callback function comes in handy:

function getInfo(callback) {
    setTimeout(() => {
      	let res = 'I am Ryan';
      	callback(res)
      	return res;
    }, 2000);
}
function showInfo(param) {
	console.log(param)
}

getInfo(showInfo) //等待2秒后:I am Ryan

Promise

What is a promise?

Promise is an object that represents the final result (complete or failed) of an asynchronous operation.
Promise is essentially an object returned by a function, we can bind the callback function to it, so that we don't need to pass the callback function as a parameter to this function at the beginning.

Example: Callback function and Promise

Callback function form

//成功回调函数
function successCallback() {
    console.log('SUCCESS')
}
//失败回调函数
function failureCallback() {
	console.log('FAILURE')
}

function myFunc(param, success, failure) {
  	if (param) {
    	success()
  	} else {
    	failure()
  	}
}

myFunc(0, successCallback, failureCallback) // FAILURE

Promise form

function myFunc(param) {
	return new Promise((resolve, reject) => {
		if (param) {
        	resolve()
      	} else {
        	reject()
      	}
	})
}

myFunc(0).then(successCallback, failureCallback) //FAILURE

Three states of promise

  • pending Initial state, neither success nor failure
  • fulfilled Operation completed successfully
  • rejected operation failed

[Note]
in the pendingstate of the object may become Promise fulfilled pass state and a value corresponding to the state processing method, and may also become a failed state (Rejected) and message delivery failure.
When either of these situations occurs, the processing method (handlers) bound to the then method of the Promise object is called (the then method contains two parameters: onfulfilled and onrejected, both of which are Function types. When the Promise state is fulfilled , Call the onfulfilled method of then, when the Promise state is rejected, call the onrejected method of then, so there is no competition between the completion of the asynchronous operation and the binding processing method)

Promise chain call

Continuous execution of two or more asynchronous operations is a common requirement. After the previous operation is successfully executed, the next operation is started, with the result returned by the previous operation.
In the past, if you want to do multiple asynchronous operations, it will lead to the classic callback hell:

// 模拟Http请求延时
function myRequest(type, callback) {
	setTimeout(() => {
      	let result = type + 1
      	callback(result)
      	return result
	}, 1000)
}
// 多重回调(仅作示例,实际情况myRequest可以是不同的函数)
myRequest(0, function (res) {
	myRequest(res, function (res) {
      	myRequest(res, function (res) {
        	console.log(res) //3
		})
	})
})

Now we can achieve this need by creating a Promise chain:

function myRequest(type) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        let result = type + 1
        resolve(result)
      }, 1000)
    })
  }
  
// 链式调用(仅作示例,实际情况myRequest可以是不同的函数)
myRequest(0).then(res => {
	return myRequest(res)
}).then(res => {
    return myRequest(res)
}).then(res => {
    console.log(res) //3
})

// 或者
myRequest(0)
.then(res => myRequest(res))
.then(res => myRequest(res))
.then(res => {
    console.log(res) //3
})

Note: there must be a return value, otherwise, callback will not get a Promiseresult. (If you use the arrow function () => xthan () => { return x; }less verbose, but the latter return wording reserved only supports the use of multiple statements.).

Published 36 original articles · won 12 · views 9413

Guess you like

Origin blog.csdn.net/qq_40738077/article/details/105376184