A Deep Dive into JavaScript Promises

A Deep Dive into JavaScript Promises

1. What is Promise?

A Promise object is like a container. It contains a piece of code that performs a specific operation. After the code is executed, two callback functions will be executed, one is the callback function for successful operation (resolve), and the other is the callback function for failed operation (reject).

2. Why is there Promise?

Promise was created to solve several problems with the callback mechanism used in asynchronous programming:

  • Callback hell

Callback hell: Promise can turn nested callbacks into .then().then()…, making code writing and reading more intuitive

  • Difficult error handling: Promise is clearer and more intuitive than callback in error handling
  • It is difficult to write code that performs multiple asynchronous operations at the same time: Promises can easily handle this situation

Three Promise common APIs

  • After the .then() method in promise is executed, it can be executed. It has two parameters, the callback function for success and the callback function for failure.
  • resolve Use the promise.resolve method to quickly return a promise object
  • reject Use the promise.reject method to quickly return a promise object
  • all Executes multiple parallel asynchronous operations simultaneously.

Four Promise common usages

1 How to solve callback hell?

.then() is a function that does not return a value, which will cause the Promise chain to no longer continue. At this time, calling .then() later will have no effect.

Promise.resolve('foo').then(function(s) {
  console.log(s);
}).then(function(s) {
  // Never executed
  console.log(s);
});

There is a return value function in .then(), which allows the Promise chain to continue

Promise.resolve('foo').then(function(s) {
  console.log(s);
  return s + 'bar';
}).then(function(s) {
  console.log(s);
});

// foo
// foobar

.then() has a function that returns a value and the return value is another Promise object, which will also make the Promise continue. The difference from the former is that calling .then() again may trigger an asynchronous operation, so the next round of resolve() is not triggered immediately.

Promise.resolve('foo').then(function(s) {
  return new Promise((resolve, reject) => {
      console.log(s);
      setTimeout(() => {
          resolve(s + 'bar')
        }, 1000);
    });
}).then(function(s) {
  console.log(s);
});


// foo
// foobar (displayed 1 second after "foo" is displayed)

2 Promise.all() implements concurrent synchronous reception of return values ​​Application scenario description (You need to call data from multiple interfaces at the same time and process the data on the front end, which requires waiting for all interfaces to return data before operating.)

//demo
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});
 
Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

Difference between Promise.all() and sync await

//sync await operation time 2 seconds async function Index2() {
      console.time()
      const p1 = await new Promise((resolve, reject) => {
        console.log('Here is p1')
        setTimeout(() => {
          resolve('Here is the return of p1')
        }, 1000)
      })
      const p2 = await new Promise((resolve, reject) => {
        console.log('Here is p2')
        setTimeout(() => {
          resolve('Here is the return of p2')
        }, 1000)
      })
      console.log(p1)
      console.log(p2) 
      console.timeEnd()
   }
    Index2();

insert image description here

// Use Promise.all() to implement the call. Operation time 1 second function Index() {
      console.time()
      const p1 = new Promise((resolve, reject) => {
        console.log('Here is p1')
        setTimeout(() => {
          resolve('Here is the return of p1')
        }, 1000)
      })
      const p2 = new Promise((resolve, reject) => {
        console.log('Here is p2')
        setTimeout(() => {
          resolve('Here is the return of p2')
        }, 1000)
      })
      Promise.all([p1, p2]).then((val) => {
        console.log(val)
        console.timeEnd()
      })
}

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of Promises in JavaScript
  • Front-end JavaScript Promise
  • JS 9 Promise Interview Questions
  • How to add abort function to promise in JS
  • Thoroughly understand JavaScript's Promise

<<:  A designer complains about Hammer's official website again

>>:  Basic knowledge of MySQL database

Recommend

HTML table tag tutorial (44): table header tag

<br />In order to clearly distinguish the ta...

How to set static IP for Ubuntu 18.04 Server

1. Background Netplan is a new command-line netwo...

Vue+ElementUI implements paging function-mysql data

Table of contents 1. Problem 2. Solution 2.1 Pagi...

How to allow external network access to mysql and modify mysql account password

The root account of mysql, I usually use localhos...

Use of MySQL official export tool mysqlpump

Table of contents Introduction Instructions Actua...

Share 8 very useful CSS development tools

CSS3 Patterns Gallery This CSS3 pattern library s...

Detailed explanation of the execution process of mysql update statement

There was an article about the execution process ...

Docker exec executes multiple commands

The docker exec command can execute commands in a...

How to hide and forge version number in Nginx

1. Use curl command to access by default: # curl ...

Several ways to easily traverse object properties in JS

Table of contents 1. Self-enumerable properties 2...

Summary of the differences and usage of plugins and components in Vue

The operating environment of this tutorial: Windo...

A complete guide to the Docker command line (18 things you have to know)

Preface A Docker image consists of a Dockerfile a...

User-centered design

I've been asked a lot lately about an apparen...