详解promise

为什么需要promise

如果你使用过jQuery中的$.promise()、angular中的$q、那么你应该熟悉异步编程模式。promise是ES6中提出的第一种解决异步编程的方案、目的是为了解决在异步编程中出现地狱回调。地狱回调非常难看而且不易于维护。

先看一个最简单的例子:

    function Ajax(time) {
        return new Promise( (resolve, reject) => {
            setTimeout( () => {
                console.log('will be success');
                resolve('success');
            }, time)
        })
    }
    let ajax = new Ajax(2000);
    ajax.then( res => {
        console.log(res);
    }, res => {
        console.log(res)
    })
原文地址:https://www.cnblogs.com/noper/p/6759434.html