代码之家  ›  专栏  ›  技术社区  ›  Scott Baker

如何在Javascript中进行多个异步调用以更新UI而不阻塞?

  •  0
  • Scott Baker  · 技术社区  · 4 年前

    我在一个网页上有几个dropdownlists,它们通过对服务器的api调用来检索内容,这些调用都非常快,另外还有一个调用从数据库检索1000行,响应时间要长得多。我有一个Javascript/Vue代码,在加载所有内容并准备就绪时运行:

    setOrderStatuses: async function () {
        this.orderStatusesLoading = true;
        this.orderStatuses = await this.getOrderStatuses();
        this.orderStatusesLoading = false;
    },
    setSpecialOrders: async function () {
        this.specialOrdersAreLoading = true;
        this.specialOrders = await this.getSpecialOrders();
        this.specialOrdersAreLoading = false;
    },
    setSubmitterNames: async function () {
        this.submitterNamesLoading = true;
        this.submitterNames = await this.getSubmitters();
        this.submitterNamesLoading = false;
    },
    ...
    mounted: function () {
       this.$nextTick(async function () {
          return await Promise.all([
             this.setOrderStatuses(),
             this.setSpecialOrders(),
             this.setSubmitterNames()
          ]);
       });
    },
    

    …其中所有内容都按预期检索数据,但UI直到 许多承诺都实现了。如果我在服务器上设置一个断点,阻止对 setOrderStatuses() ,例如,在我单击之前,其他方法都不会更新UI continue 承诺也实现了。

    1 回复  |  直到 4 年前
        1
  •  0
  •   viryl15    4 年前

    JU使您的mouted方法异步,如:

    async mounted () {
       await this.setOrderStatuses()
       await this.setSpecialOrders()
       await this.setSubmitterNames()
    }