zyanfei
9/18/2018 - 5:48 AM

promise demo

promise demo

// Promise
// promise封装在function里
function runAsync(){
    return new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            console.log('执行完成');
            resolve('随便什么数据');
        }, 2000);
    });         
}
runAsync()
  
runAsync().then(function(data){
    console.log(data);
    //后面可以用传过来的数据做些其他操作
    //......
});
  
// 单独定义promise
$(function() {
    new Promise(function(resolve, reject) {
        if (1) {
            console.log('执行完成');
            resolve('随便什么数据');
        } else {
            reject('错误');
        }
    }).then(function(data) {
        console.info(data);
    }).catch(function(error) {
        console.info(error);
    })
})
 
// Promise中then的链式操作
Promise.resolve("foo")
  // 1. 接收 "foo" 并与 "bar" 拼接,并将其结果做为下一个reslove返回。
  //  then 里面return ajax请求后的 结果
  .then(function(string) {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        string += 'bar';
        resolve(string);
      }, 1);
    });
  })
  // 2. 接收 "foobar", 放入一个异步函数中处理该字符串
  // 并将其打印到控制台中, 但是不将处理后的字符串返回到下一个。
  .then(function(string) {
    setTimeout(function() {
      string += 'baz';
      console.log(string); //foobarbaz
    }, 1)
    return string;
  })
  // 3. 打印本节中代码将如何运行的帮助消息,
  // 字符串实际上是由上一个回调函数之前的那块异步代码处理的。
  .then(function(string) {
    console.log("Last Then:  oops... didn't bother to instantiate and return " +
                "a promise in the prior then so the sequence may be a bit " +
                "surprising");
  
    // 注意 `string` 这时不会存在 'baz'。
    // 因为这是发生在我们通过setTimeout模拟的异步函数中。
    console.log(string);  //foobar
});


// Promise all

let p1 = new Promise((resolve, reject) => {
  resolve('成功了')
})
 
let p2 = new Promise((resolve, reject) => {
  resolve('success')
})
 
let p3 = Promse.reject('失败')
 
Promise.all([p1, p2]).then((result) => {
  console.log(result)               //['成功了', 'success']
}).catch((error) => {
  console.log(error)
})
 
Promise.all([p1,p3,p2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error)      // 失败了,打出 '失败'
})