Promise簡單使用,須要在ES6以上

var waitSecond = new Promise(function(resolve, reject) {
    setTimeout(resolve, 1000);
});
waitSecond.then(function() {
    console.log("Hello"); // 1秒後輸出"Hello"
    return waitSecond;
}).then(function() {
    console.log("Hi"); // 2秒後輸出"Hi"
});

 

new Promise(function(resolve , reject) {
    resolve(1);
}).then(function(val) {
    console.log(val);
    return new Promise(function(resolve , reject) {
        resolve(2);
    });
}).then(function(val) {
    console.log(val);
    return new Promise(function(resolve , reject) {
        resolve(3);
    });
}).then(function(val) {
    console.log(val);
    return new Promise(function(resolve , reject) {
        resolve(4);
    });
}).then(function(val) {
    console.log(val);
});

//輸出:
//      1
//      2
//      3
//      4

 

下面代碼中,setTimeout(fn, 0)在下一輪「事件循環」開始時執行,Promise.resolve()在本輪「事件循環」結束時執行,console.log('one')則是當即執行,所以最早輸出。 
setTimeout(function () {
  console.log('three');
}, 0);

Promise.resolve().then(function () {
  console.log('two');
});

console.log('one');
相關文章
相關標籤/搜索