ES6 Promise you know how to use, promise usage

What is promise?

1. Mainly used for asynchronous calculation
2. It can queue asynchronous operations, execute in the desired order, and return the expected result
3. Can pass and operate promises between objects to help us process the queue

To avoid freezing of the interface (task)

  • Synchronization: Suppose you go to a restaurant, find a location, and call the waiter. At this time, the waiter tells you, I'm sorry I am a "synchronization" waiter, and I have to finish serving this table before I can greet you. The guests at that table obviously have already eaten, you just want a menu, such a small action, but the waiter wants you to wait until someone else's big action is completed before they come to greet you again. This is a synchronization problem: that is, "order" The work delivered 1234 must be completed in the order of 1234".

  • Asynchronous: After handing over the time-consuming work delivered by A to the system, continue to do the work delivered by B. After the system has completed the previous work, it can continue to do the remaining work of A through callbacks or events.
    The order of completion of AB's work has nothing to do with the order of delivery of them, so it is called "asynchronous".

Basic grammar

new Promise(
  function (resolve, reject) {
    // 一段耗时的异步操作
    resolve('成功') // 数据处理完成
    // reject('失败') // 数据处理出错
  }
).then(
  (res) => {console.log(res)},  // 成功
  (err) => {console.log(err)} // 失败
)

Let's take a look at the simplest Promise example: Generate a random number between 0 and 2. If it is less than 1, wait for a period of time and return success, otherwise return failure:

function test(resolve, reject) {
    var timeOut = Math.random() * 2;
    log('set timeout to: ' + timeOut + ' seconds.');
    setTimeout(function () {
        if (timeOut < 1) {
            log('call resolve()...');
            resolve('200 OK');
        }
        else {
            log('call reject()...');
            reject('timeout in ' + timeOut + ' seconds.');
        }
    }, timeOut * 1000);
}

This test()function has two parameters, these two parameters are functions, if the execution is successful, we will call resolve('200 OK'), if the execution fails, we will call reject('timeout in ' + timeOut + ' seconds.'). It can be seen that the test()function only cares about its own logic, and does not care about the specifics resolveand rejecthow to deal with the results.

With the execution function, we can use a Promise object to execute it and get a success or failure result at some point in the future:

var p1 = new Promise(test);
var p2 = p1.then(function (result) {
    console.log('成功:' + result);
});
var p3 = p2.catch(function (reason) {
    console.log('失败:' + reason);
});

The variable p1is a Promise object, which is responsible for executing the testfunction. Since the testfunction is executed asynchronously internally, when the testfunction is successfully executed, we tell the Promise object:

// 如果成功,执行这个函数:
p1.then(function (result) {
    console.log('成功:' + result);
});

When the testfunction fails, we tell the Promise object:

p2.catch(function (reason) {
    console.log('失败:' + reason);
});

Promise objects can be chained together, so the above code can be simplified to:

 

new Promise(test).then(function (result) {
    console.log('成功:' + result);
}).catch(function (reason) {
    console.log('失败:' + reason);
});

Wherejob1 , job2and job3are subject Promise.

The following example demonstrates how to serially execute a series of tasks that require asynchronous calculations to obtain results:

'use strict'; var logging = document.getElementById('test-promise2-log'); while (logging.children.length > 1) { logging.removeChild(logging.children[logging.children.length - 1]); } function log(s) { var p = document.createElement('p'); p.innerHTML = s; logging.appendChild(p); } 

// 0.5秒后返回input*input的计算结果:
function multiply(input) {
    return new Promise(function (resolve, reject) {
        log('calculating ' + input + ' x ' + input + '...');
        setTimeout(resolve, 500, input * input);
    });
}

// 0.5秒后返回input+input的计算结果:
function add(input) {
    return new Promise(function (resolve, reject) {
        log('calculating ' + input + ' + ' + input + '...');
        setTimeout(resolve, 500, input + input);
    });
}

var p = new Promise(function (resolve, reject) {
    log('start new Promise...');
    resolve(123);
});

p.then(multiply)
 .then(add)
 .then(multiply)
 .then(add)
 .then(function (result) {
    log('Got value: ' + result);
});

 

In addition to executing several asynchronous tasks serially, Promise can also execute asynchronous tasks in parallel.

Imagine a page chat system. We need to obtain the user's personal information and friend list from two different URLs. These two tasks can be performed in parallel. The Promise.all()implementation is as follows:

var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
// 同时执行p1和p2,并在它们都完成后执行then:
Promise.all([p1, p2]).then(function (results) {
    console.log(results); // 获得一个Array: ['P1', 'P2']
});

Sometimes, multiple asynchronous tasks are for fault tolerance. For example, to read the user's personal information to two URLs at the same time, you only need to get the result returned first. In this case, use Promise.race():

var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
Promise.race([p1, p2]).then(function (result) {
    console.log(result); // 'P1'
});

Due p1to the faster execution, Promise then()will get the result 'P1'. p2The execution continues, but the execution result will be discarded.

If we use Promise in combination, we can combine many asynchronous tasks to execute in parallel and serial.

 

Guess you like

Origin blog.csdn.net/qq_39418742/article/details/106314769