解決方案:
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)