回调函数之基本的Promise

在 JavaScript 中,所有的代码都是单线程的,所谓的回调函数就是为了处理一些异步的操作。而多层的回调函数嵌套是一种比较古老的处理方式,这种代码的弊端显而易见,结构混乱、代码冗余,而 Promise 的出现就很好的解决了这个问题;

基本 Promise

function fn(n) {
    return new Promise(function(resolve, reject) {
        var nubmer = 0.5;
        if (n > nubmer) {
            resolve('greater than 0.5s')
        } else {
            reject('less than 0.5s')
        }
    })
}

var p = fn(Math.random());
p.then((res) => {
    console.log(res);
}).catch(err => {
    console.log(err);
})

链式调用

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

// 0.5秒后返回input+input的计算结果:
function add(input) {
    return new Promise(function(resolve, reject) {
        console.log('calculating ' + input + ' + ' + input + '...');
        setTimeout(resolve(input + input), 500);
    });
}
p.then(multiply).then(add).then(res => {
    console.log('Got value: ' + res);
}).catch(e => {
    console.log(e);
})

// 得到结果
start new Promise...
calculating 10 x 10...
calculating 100 + 100...
Got value: 200

Promise 封装 Ajax

// ajax函数将返回Promise对象:
function ajax(method, url, data) {
    var request = new XMLHttpRequest();
    return new Promise(function(resolve, reject) {
        request.onreadystatechange = function() {
            if (request.readyState === 4) {
                if (request.status === 200) {
                    resolve(request.responseText);
                } else {
                    reject(request.status);
                }
            }
        };
        request.open(method, url);
        request.send(data);
    });
}
// 调用 
var p = ajax('GET', url).then(function(text) { // 如果AJAX成功,获得响应内容
    console.log(text);
}).catch(function(status) { // 如果AJAX失败,获得响应代码
    console.log('ERROR: ' + status);
});

猜你喜欢

转载自www.cnblogs.com/jone-chen/p/10517912.html