Aren't asynchronous functions supported in the constructor of the js class?

classPClocalStorage
cookielocalStorage
`
    class ShopCarTool{
      constructor(store){
       // var shopCar = DB.getItem("shop-car").toJson()// localStorage
        /*  */
        let shopCar={};
        axios.get(url).then(res=>{
            shopCar=res.data
        })
        if(!shopCar){
          DB.setItem("shop-car", JSON.stringify(shopCar = {}))
        }
        this.$store = store
        this.shopCarDB = shopCar
      }
      length() {//
        var n = 0;
        for(var i in this.shopCarDB){
          n += this.shopCarDB[i].length
        }
        return n
      }
    }

`

    localStorageshopCarDB 
    length()!
    ![][1]
    length()shopCarDB
     constructor

new Promiselength()this.shopCarDB = shopCar
localStorage

Apr.11,2021

if it is an ordinary function, you can use async and await to solve your problem
but this is in constructor. The function of constructor is to return an object instance. If you add async, it will return a promise, so this method does not work, because it cannot return both a promise and an object instance

.

you can use a workaround

class ShopCarTool{
      constructor(storefrom_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
      }
    }

var tool = await ShopCarTool.build(store)

tips: code has not been strictly verified, that's what it means. Don't copy

.

generally speaking, if there is an operation that needs to be initialized asynchronously. All the asynchronous functions are called in constructor, and events are used to remind the outside after initialization. The outside only needs to listen to the event. If it is a non-event object, the external can write an extra await his initialization function to complete the asynchronous data call.

another answer is also a good way to get the initialization data in advance through a function and then instantiate the class

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b38a8f-2c14a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b38a8f-2c14a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?