Promise

var promise = new Promise(function(resolve, reject) {
    var flag = Math.random();
    console.log(1);
    setTimeout(function() {
        if(flag<0.1) {
            resolve('success');
        }
        else {
            reject('fail');
        }
    }, 1000);
    console.log(2);
});
console.log(promise);
// 执行顺序 1  2 promise { [native code] }
// catch(func) 就是 then(null,func)
promise.then(function(){
    console.log(arguments)
},function(){
    console.log("===>",arguments)
    throw 123;
    return arguments;
}).catch(function(){
    console.log("00000==<<>>>  ",arguments)
    return 12;
}).then(function(){
    console.log("-----=  ",arguments)
});

const arr = [
    new Promise(function(resolve, reject) {
    setTimeout(function() {
       resolve('1')
    }, 200);
}),new Promise(function(resolve, reject) {
    setTimeout(function() {
        
       resolve('2')
    }, 400);
}),new Promise(function(resolve, reject) {
    setTimeout(function() {
       
       resolve('3')
    }, 500);
}),new Promise(function(resolve, reject) {
    setTimeout(function() {
        
       resolve('4')
    }, 500);
}),new Promise(function(resolve, reject) {
    setTimeout(function() {
       
       resolve('5')
    }, 0);
})];
// const arr = [promise,promise,promise,promise]
// 所有都完成(成功) 或 第一个失败 失败一个就不会等待其他是否完成 顺序返回
const p2 = Promise.all(arr);

p2.then(function(){
    console.log("1==>  ",arguments);
}).catch(function(){
     console.log("2==>  ",arguments);
}).then(function(){
    console.log("3==>  ",arguments);
}).catch(function(){
     console.log("4==>  ",arguments);
});

var promise1 = new Promise(function(resolve, reject) {
    setTimeout(reject, 50, 'one');
});

var promise2 = new Promise(function(resolve, reject) {
    setTimeout(reject, 100, 'two');
});
// 谁反应快就返回谁 不管是resolve 还是reject
Promise.race([promise1, promise2]).then(function(value) {
  console.log(value);
  // Both resolve, but promise2 is faster
}).catch(function(value) {
  console.log("1",value);
  // Both resolve, but promise2 is faster
});