验证Promise是同步的

Table of Contents

前言

Promise是ES6提出的解决异步编程导致陷入回调的地狱问题。

例子1

console.log(1);
var a=new Promise(function(resolve, reject){
    console.log(2);
    resolve();
});
console.log(2);
var b = new Promise(function(resolve, reject){
    console.log(4);
    resolve();
});
console.log(5);
a.then(function(){
    console.log(6);
});
b.then(function(){
    console.log(7);
});

顺序输出:1~7

例子2

console.log(1);
    var a = new Promise(function(resolve, reject){
    resolve();
    console.log(2);
});
a.then(function(){
    console.log(6);
});
console.log(3);
var b = new Promise(function(resolve, reject){
    resolve();
    console.log(4);
});
b.then(function(){
    console.log(7);
});
console.log(5);

顺序输出:1~7

结论

Promise本身是同步的,但.then和.catch方法是异步的