Why use promise

Original text: Why use promise

 

cause

As we all know, the most headache of front-end development is to deal with asynchronous requests. Continue to write functions in the successful callback function, and in the long run, callback hell has formed.

function load() {
    $.ajax({
        url: 'xxx.com',
        data: 'jsonp',
        success: function(res) {
            init(res, function(res) {
                render(res, function(res) {
                    // Layer by layer
                });
            });
        }
    }
}

load();

This kind of code level is small, of course, or can make do with, but more, it is difficult to maintain, whether developers themselves or colleagues to take over the project, are extremely helpless! How I want to be, how I want to be, how I want to be, how I want to be.

So there's Promise

When I heard about Promise, I didn't pay much attention. I only knew that it was an asynchronous request solution to solve the problem of callback to hell. Later, it was found that JQ also implemented the relevant methods in the work

$.get('xxx.php').done(function() {
    alert('Successful callback');    // Equivalent to Promise's resolve()
});

Now it looks like Promise. So let's go back to today's protagonist

First, introduce three states of Promise:

  • Pending
  • Fulfilled succeeded
  • Rejected failed

After that, the status goes directly to the code. We have to be able to use it:

Also take the example of the load function above

  // then method is the most used
  // Execute successful and failed callback functions according to then
  function load() {
    return new Promise((resovel, reject) => {
        $.ajax({
            url: 'xxx.com',
            data: 'jsonp',
            success: function(res) {
                resolve(res);
            },
            error: function(err) {
                reject(err);
            }
        });
    });
}

// Use it.
load().then(data => {
    console.log(data);  // Data requested to
    console.log('Request data successful');
}, err => {
    console.log('request was aborted');
});

In addition to processing requests, Promise can also be written in normal functions

function init(options) {
    return new Promise((resolve, reject) => {
        if (options.id) {
            console.log('You are the only one.')
            resolve(options.id);
        } else {
            console.log('No, no');
            reject()
        }
    });
}

init({id: 110})
    .then(id => {
        console.log(id);          // 110
        let obj = {id, nickname: 'Zuo Xi'};
        return obj;
    })
    .then(other => {
        console.log(other);    // {id: 110, nickname: 'Zuoshi'}
    });

Promise.all is similar to Promise.race

all indicates success only when Promise status is success

race is the state of Promise. If there is a state of first success, it means success

Recently, the popular axios actually called Promise, and the writing method is very similar

Because it is a third-party package, npm i axios needs to be installed

// Send a get request
axios.get('user/', {
    id,
    username
}).then(res => {
    console.log(res);   // Success
}).catch(err => {
    console.log(err);   // fail
});

// Another post request
axios.post('login/', {
    username,
    password
}).then(res => {
    console.log(res);   // Success
}).catch(err => {
    console.log(err);   // fail
});

// There are also all operations
function getUser() {
    return axios.get('/user');
}

function sendMsg() {
    return axios.post('/info', {msg});
}

axios.all([getUser(), sendMsg()]).then(res => {})

Here's a summary: Promise is commonly used. then returns a Promise object, so you can continue to call the. then method.

 

Tags: axios PHP npm

Posted on Fri, 31 Jan 2020 13:30:37 -0800 by sdotsen