微信小程序上 promise 使用


 

1、引用此js,沒有自行百度

 import regeneratorRuntime from "sudu8_page/resource/js/runtime.js";

 

2、js代碼:

//一、同步執行: async await 關鍵詞

調用方也得加 async

 

async testAsync() {
const result = await this.testPromise()
console.log('async test--', result)    
},

testPromise() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('Promise handle')
          resolve(1234)
        }, 2000)
      })
    },  
 
打印輸出

Promise handle  
async test-- 1234 

//二、簡單的

testPromise() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('Promise handle')
          resolve(1234)  //提前返回回去,表示正確數據 then res
          //reject(33333)  //提前返回回去,表示異常內容 catch   err
        }, 2000)
      })
    },  
 
a:function(){
this.testPromise().then(res=>{
console.log(res)
}).catch(function(err){
console.log(err)  //如果有 reject 則打印這個的值
})
}

打印:

1234

or

33333

   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM