Javascript異步編程

      Javascript語言將任務的執行模式分紅兩種:同步(Synchronous)和異步(Asynchronous)。"同步模式":後一個任務等待前一個任務結束,而後再執行,程序的執行順序與任務的排列順序是一致的、同步的。"異步模式":每個任務有一個或多個回調函數(callback),前一個任務結束後,不是執行後一個任務,而是執行回調函數,後一個任務則是不等前一個任務結束就執行,因此程序的執行順序與任務的排列順序是不一致的、異步的。 常見的異步操做:網絡請求(ajax http.get)、定時函數(setTimeout setInterval)、事件監聽和處理。
      1、回調函數
function getUserInput(firstName, lastName, callback)  {
    // Do other stuff to validate firstName/lastName here
    // Now save the names
    if(callback && (callback  instanceof Function){
        callback (firstName, lastName);
    }
}
      回調函數的優勢是簡單、容易理解和部署,缺點是不利於代碼的閱讀和維護。
      2、事件監聽
f1.on('done', f2);
 
function f1(){
   setTimeout(function () {
    // f1的任務代碼
    f1.trigger('done');
  }, 1000);
}
      3、jquery deferred對象
      jQuery規定,deferred對象有三種執行狀態----未完成,已完成和已失敗。若是執行狀態是"已完成"(resolved),deferred對象馬上調用done()方法指定的回調函數;若是執行狀態是"已失敗",調用fail()方法指定的回調函數;若是執行狀態是"未完成",則繼續等待。
var wait = function(dtd){
  var dtd = $.Deferred(); //在函數內部,新建一個Deferred對象
  var tasks = function(){
    alert("執行完畢!");
    dtd.resolve(); // 改變Deferred對象的執行狀態
  };
  setTimeout(tasks,5000);
  return dtd.promise(); // 返回promise對象
};
$.when(wait())
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出錯啦!"); });

       四、Promise對象javascript

       一、定義
             Promise 是一個對象,從它能夠獲取異步操做的消息。 一旦狀態改變,就不會再變,任什麼時候候均可以獲得這個結果。
        二、基本用法
function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms, 'done');
  });
}
 
timeout(100).then(function(value) {
  // success
}, function(error) {
  // failure
});
      三、Promise.prototype.then()
            Promise 實例添加狀態改變時的回調函數。
function add(x1, x2) {
    return new Promise(function (resolve, reject) {
        var res = x1 + x2;
        console.log(res);
        resolve(res);
    });
}
add(1, 2).then(function (res) {
    return add(3, 4);
}).then(function () {
    return add(4,5);
})
四、Promise.prototype.catch()
      Promise.prototype.catch方法是.then(null, rejection)的別名,用於指定發生錯誤時的回調函數。
getJSON('/posts.json').then(function(posts) {
  // ...
}).catch(function(error) {
  // 處理 getJSON 和 前一個回調函數運行時發生的錯誤
  console.log('發生錯誤!', error);
});
五、Promise.all()
     Promise.all方法用於將多個 Promise 實例,包裝成一個新的 Promise 實例。
const p1 = new Promise((resolve, reject) => {
  resolve('hello');
})
.then(result => result)
.catch(e => e);
const p2 = new Promise((resolve, reject) => {
  throw new Error('報錯了');
})
.then(result => result)
.catch(e => e);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
 
相關文章
相關標籤/搜索