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');
相关文章
相关标签/搜索