Callback Hell and ECMAScript6 Promise

Keywords: Front-end P4 Javascript

Promise is the fifth day of "14nodejs (7 days)", but promise is not the content of Node.js, but the new API of ECMScript6

Callback Hell

Callback region one asynchronous request needs another asynchronous request result

$.ajax({url, success: function () { ... }})
$.ajax({url, success: function () { ... }})
$.ajax({url, success: function () { ... }})
$.ajax({url, success: function () { ... }})

Because Javascript is single threaded, the execution order here is ajax1 - > ajax2 - > ajax3 - > ajax4

But because these four operations are asynchronous, this kind of multithreading operation will lead to the execution order is not fixed

In order to ensure the execution order of asynchronous functions, it can be solved by asynchronous nested asynchronous

$.ajax({url, success: function () {
    $.ajax({url, success: function () {
		$.ajax({url, success: function () {
			$.ajax({url, success: function () { ... }})
    	}})
    }}) 
}})

The above method is called callback region, which is very difficult to maintain

To solve this problem, ECMAScript6 has added Promise API

Promise (promise)

It can be understood that project is a container, which contains three states: pending, Resolved, and Rejected

Promise itself is not asynchronous, but the content function of its package is asynchronous

// Create Promise container with new Promise
// Instantiate Promise
var p1 = new Promise (function (resolve, reject) { // Promise container (it is not an asynchronous method by itself)
    $.ajax({ // $. ajax asynchronous method
        url,
        success: function () {
            resolve(data) // Change container state to success
        },
        error: function () {
        	reject(err) // Failed to change container state
        }
    })
})

The container receives two parameters:

  • resolve change container state to success
  • reject failed to change the container state

Determine the specified operation after the instance succeeds through. then()

p1.then(function (data) {
    console.log(data) // Receive the data thrown by resolution in p1 instance success status 
    return p2 // Return to the second Promise container
}, function (err) {
    console.log(err) // Receive data thrown by reject in p1 instance failure status
})

. then contains two function parameters:

  • The parameters of the first function receive the successful content thrown by resolve in the Promise container
  • The parameter of the second function receives the failure information thrown by reject in the Promise container

Data can be returned in the first function of. then, which can be used by subsequent. then receivers

  • If there is no return value, undefined will be received later
  • If return returns a Promise object, the next. then first function receives the resolve state of the Promise object, and the second function receives the reject state of the Promise object

Here, you can optimize callback hells through the above introduction

// Create Promise container with new Promise
// Instantiate Promise
var p1 = new Promise (function (resolve, reject) { // Promise container (it is not an asynchronous method by itself)
    $.ajax({ // $. ajax asynchronous method
        url,
        success: function () {
            resolve(data) // Change container state to success
        },
        error: function () {
        	reject(err) // Failed to change container state
        }
    })
})
var p2 = new Promise (function (resolve, reject) { ... })
var p3 = new Promise (function (resolve, reject) { ... })
var p4 = new Promise (function (resolve, reject) { ... })
// Operation instance
p1
    .then(function (data) {
        console.log(data) // Print the data content of p1
        return p2 // Pass down instance p2
    }, function (err) {
        console.log(err) // Print the err information of p1
    })
    .then(function (data) {
        console.log(data) // Print data content of p2
        return p3 // Pass down instance p3
    }, function (err) {
        console.log(err) // Print the err information of p2
    })
    .then(function (data) {
        console.log(data) // Print data content of p3
        return p4 // Pass down instance p4
    }, function (err) {
        console.log(err) // Print err information of p3
    })
    .then(function (data) {
        console.log(data) // Print the data content of p4
    }, function (err) {
        console.log(err) // Print the err information of p4
    })

Judge whether it is a Promise object by judging whether there is a then method

var p1 = new Promise (function (resolve, reject) { ... }
function p2 () { ... }
// Replace fn in the next code to see if P1 and P2 are Promise objects
if (!!fn && typeof fn.then === 'function') {
    console.log('yes Promise')
} else {
    console.log('No Promise')
}

Article synced to my personal blog:< Callback Hell and ECMAScript6 Promise>

Reference:

This article is based on the platform of blog one article multiple sending OpenWrite release!

Posted by macdumbpling on Thu, 19 Dec 2019 22:51:46 -0800