gpt4 book ai didi

javascript - 在等待 promise 完成时无法在 Vue.js 中获取 DOM 更新

转载 作者:行者123 更新时间:2023-11-30 19:07:40 33 4
gpt4 key购买 nike

我对 JS promises 不是很精通,虽然我通常知道足够危险。我正在研究 Vue 方法,该方法处理 this.data() 中存在的大型数据对象的搜索 - 通常当我通过 axios 发出异步请求时,同样的格式可以正常工作,但在这种情况下我必须手动创建 promise 以获得所需的行为。这是代码示例:

        async searchPresets() {

if (this.presetSearchLoading) {
return
}

this.presetSearchLoading = true; // shows spinner
this.presetSearchResults = []; // removes old results
this.selectedPresetImports = []; // removes old user sections from results

// Need the DOM to update here while waiting for promise to complete
// otherwise there is no "loading spinner" feedback to the user.
const results = await new Promise(resolve => {

let resultSet = [];
for (var x = 0; x < 10000; x++) {
console.log(x);
}

let searchResults = [];
// do search stuff
resolve(searchResults);

});

// stuff after promise

}

问题是,promise 之后的东西可以正常工作。它在执行之前等待解决方案,并按原样接收正确的搜索结果数据。

问题是 DOM 不会在发送 promise 时更新,所以 UI 只是停留在那里。

有人知道我做错了什么吗?

最佳答案

尝试$nextTick():

Vue 2.1.0+:

const results = await this.$nextTick().then(() => {                      
let resultSet = []
for (var x = 0; x < 10000; x++) {
console.log(x)
}

let searchResults = []
// do search stuff
return searchResults
});

任何 Vue:

const results = await new Promise(resolve => {                      
this.$nextTick(() => {
let resultSet = []
for (var x = 0; x < 10000; x++) {
console.log(x)
}

let searchResults = []
// do search stuff
resolve(searchResults)
})
})

关于javascript - 在等待 promise 完成时无法在 Vue.js 中获取 DOM 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58828474/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com