Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vue front-end interaction mode, Promise usage (callback hell)


May 30, 2021 Article blog



General Overview of Promise

Promise is a solution for asynchronous programming, and grammatically, Promise is an object from which you can get messages about asynchronous operations.

merit:

  • Avoid multi-layered asynchronous call nesting issues (callback hell)
  • The Promise object provides a clean API that makes it easier to control asynchronous operations

Promise basic usage

  • Instantiates the Promise object, a pass-through function in the constructor that handles asynchronous tasks
  • The resolve and reject parameters are used to handle both successful and failed cases and get the results through p.then
var p = new Promise(function(resolve,reject){
    //实现异步任务...
    //成功时调用
    resolve();
    //失败时调用
    reject();
});
p.then(function(ret){
    //从resolve得到正常结果
},function(ret){
    //从reject得到错误信息
});  

Process Ajax requests based on Promise

  1. Handle native Ajax
function queryData(url){
    return new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState!=4) return;
            if(xhr.status == 200){
                resolve(xhr.responseText);
            }else{
                reject('出错了');
            }
        }
        xhr.open('get',url);
        xhr.send(null);
    });
}
//调用
queryData('http://localhost:3000/data').then(
    function (data) {
        console.log(data);
    },
    function (data) {
        console.log(data);
    }
)
  1. Send multiple ajax requests (resolve callback hell)
queryData('http://localhost:3000/data')
    .then(function (data) {
        console.log(data);
        //异常情况可以不处理
        return queryData('http://localhost:3000/data1');
    })
    .then(function (data1) {
        console.log(data1);
        return queryData('http://localhost:3000/data2');
    })
    .then(function (data2) {
        console.log(data2);
    });

The function in the then argument returns a value

  1. The instance object returned by the Return instance object calls the next then
  2. The normal value returned by returning a normal value is passed directly to the next then, which receives the value through the parameters of the function in the then argument

The API commonly used by Promise

1. Instance method

* p.then()得到异步任务的正确结果
* p.catch()获取异常信息
* p.finally()成功与否都会执行(暂时还不是正式标准)
foo()
    .then(function (data) {
        console.log(data);
    })
    .catch(function (data) {
        console.log(data);
    })
    .finally(function () {
        console.log('finish');
    })

It can also be written as:

foo()
    .then(function (data) {
        console.log(data);
    },
    function (data) {
        console.log(data);
    })
    .finally(function () {
        console.log('finish');
    })  

2. Object method

  • Promise.all() handles multiple asynchronous tasks concurrently, all of which are performed to get results
//p1,p2,p3为Promise实例对象任务
Promise.all([p1,p2,p3]).then((result)=>{
    console.log(result);
})
  • Promise.race() handles multiple asynchronous tasks concurrently, and results can be obtained as long as one task is completed
Promise.race([p1,p2,p3]).then((result)=>{
    console.log(result);
})