Sloppy's Blog

ES6中的Promise

相信大家见过这种代码,有种想死的冲动,代码如下:

$.ajax({
        url: '......',
        success: function (data) {
        $.ajax({
            // 要在第一个请求成功后才可以执行下一步
            url: '......',
            success: function (data) {
                 // ......
                 $.ajax({
                    // 要在第二个请求成功后才可以执行下一步
                    url: '......',
                    success: function (data) {
                         // ......
                    }
                });
            }
        });
    }
});
如果出现多个需要执行的加调。是不是根本无法理解,想死了。下面看看ES6中的promise魅力:
function printHello (ready) {
    return new Promise(function (resolve, reject) {
        if (ready) {
            resolve("Hello");
        } else {
            reject("Good bye!");
        }
    });
}

function printWorld () {
    alert("World");
}

function printExclamation () {
    alert("!");
}

printHello(true)
    .then(function(message){
        alert(message);
    })
    .then(printWorld)
    .then(printExclamation);

还可以这样写:

function printHello (ready) {
    return new Promise(function (resolve, reject) {
        if (ready) {
            resolve("Hello");
        } else {
            reject("Good bye!");
        }
    });
}

printHello(false).then(function (message) {
    return message;
}).then(function (message) {
    return message  + ' World';
}).then(function (message) {
    return message + '!';
}).then(function (message) {
    console.log(message);
},function (error) {
    console.log(error);
});

当然还可以多个Promise:

var p1 = new Promise(function (resolve) {
    setTimeout(function () {
        resolve("Hello");
    }, 3000);
});

var p2 = new Promise(function (resolve) {
    setTimeout(function () {
        resolve("World");
    }, 1000);
});

Promise.all([p1, p2]).then(function (result) {
    console.log(result); // ["Hello", "World"]
});