js類的constructor中不支持異步函數嗎?


解決方案:

1.如果是普通函數,可以用async 和await來解決你的問題
但你這個是在constructor里,constructor 的作用是返回一個對像實例,如果加了async就變成返回一個promise了,所以這個方法行不通,因為做不到既返回一個promise又返回一個object 實例

eg:

class ShopCarTool{ constructor(store,from_async){ // var shopCar = DB.getItem('shop-car').toJson()// 從localStorage獲取 /* 從服務器獲取 */ if(!from_async){ DB.setItem('shop-car', JSON.stringify(shopCar = {})) } this.$store = store this.shopCarDB = from_async } static async build(store){ let data = await axios.get(url) return new ShopCarTool(store,async_result); } length() {//獲取購物車商品數量小角標 var n = 0; for(var i in this.shopCarDB){ n += this.shopCarDB[i].length } return n } }
所以你哪你要實例化也改成(tips: 代碼沒有經過嚴格驗證,就是這么個意思,)
var tool = await ShopCarTool.build(store)
 


免責聲明!

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



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