2016/03/11

$.Deferred VS Promise

Promise 是非常好用的一個特性,主要用來處理 async 的工作,在 jQuery 上很早就有 deferred 的實作,而 JavaScript ES6 也把這個功能加了進來,而且寫法非常清爽,但 ES6 要普及應該還要一段時間,jQuery 的 deferred 比較沒有相容性的問題,在這邊列一下同樣功能怎樣在雙邊實現。

單一運用

$.Deferred

let response = () => {
    return $.Deferred(dfd => {
        setTimeout(() => {
            dfd.resolve('done');
        }, 2000)
    }).promise();
}

$.when(response()).then(response => {
    console.log(response);
});

// or

let response = () => {
    let dfd = $.Deferred();

    setTimeout(() => {
        dfd.resolve('done');
    }, 2000)

    return dfd.promise();
}

$.when(response()).then(response => {
    console.log(response);
});

Promise

let response = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('done');
        }, 2000);
    });
}

response().then(response => {
    console.log(response);
});

等待多重結果

$.Deferred

let results = [];

[2000, 3000, 4000].forEach(timer => {
    results.push($.Deferred(dfd => {
        setTimeout(() => {
            console.log('single done!');
            dfd.resolve();
        }, timer);
    }));
});

$.when.apply($, results).then(() => {
    console.log('all done');
});

promise

let promises = [];

[2000, 3000, 4000].forEach(timer => {
    promises.push(new Promise(resolve => {
        setTimeout(() => {
            console.log('single promise done!');
            resolve();
        }, timer);
    }));
});

Promise.all(promises).then(() => {
    console.log('promise all done');
});

沒有留言: