H5異步編程學習筆記

     項目中使用H5做混合編程,但是還是android的那套邏輯,需要使用很多回調和異步線程間,涉及到異步和同步的處理。實際開發中使用了大量的回調,使代碼可讀性變差,擴展性降低。比如,界面啓動時,需要在網絡獲取數據,存在臨時緩存中,多個異步線程中使用這個數據。

這裏重新學習一下H5的異步編程,優化代碼邏輯

H5異步編程的方法,這篇文章說的挺詳細的

javascript 異步編程的5種方式

我使用的是 async/awai  +promis來解決 異步轉同步問題,關於promise,這篇文章講的比較清楚

JS異步編程(promise、deferred對象)

理解promise,實現異步的同步編寫

 

中文文檔

Promise

使用 Promise

 

demo1

function testPromise() {
  console.log(">>>>>11111");
  testResult();
  console.log(">>>>>22222");
}

function getPromise(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(">>>>>55555");
      resolve(2 * num)
      console.log(">>>>>666666");
    }, 200);
  } )
}

async function testResult() {
  console.log(">>>>>33333");
  let result = await getPromise(1);
  console.log(">>>>>44444>>result:"+result);

}

打印結果 

1->3->2->5->6->4

testPromise 方法中 testResult 是異步執行,不阻斷主線程

testResult 方法中 getPromise 方法有await標識,是同步方法,阻斷主線程,要等待  resolve 方法返回結果,纔回繼續執行。

getPromise 方法雖然返回的是 new Promise ,但是實際上是返回 resolve 中的值。

 

demo2

function testPromise() {
  console.log(">>>>>11111");
  var a = testResult();
  a.then(function (res) {
    console.log(">>>>>77777+res:" + res);
  })
  console.log(">>>>>22222");
}

function getPromise(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(">>>>>55555");
      resolve(2 * num)
      console.log(">>>>>666666");
    }, 200);
  } )
}

async function testResult() {
  console.log(">>>>>33333");
  let result = await getPromise(1);
  console.log(">>>>>44444>>result:"+result);
  return result
}

打印結果:

demo2 中,將 testResult 方法放回的值改爲了Promise 對象,在testPromise 獲取後執行了.then方法,這樣也能或者到放回的值

①打印的先打印2,最後打印7,testPromise 方法中 testResult 是異步執行,不阻斷主線程

 

詳細的測試也可以參考這個文章 

https://blog.csdn.net/qq_32899575/article/details/83107587

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章