【发布时间】:2021-06-09 08:00:06
【问题描述】:
我想异步初始化一个 ViewModel。我不是指异步加载 ViewModel,我已经管理了(见下面的代码)。
ViewModel 将被异步加载一次。之后,我想根据提供给 ViewModel 的参数做一些异步操作。看起来在获得参数后,您必须同步返回 ViewModel,不支持承诺/回调系统。 请看下面的代码:
const defaultLoader: KnockoutComponentTypes.Loader = {
loadViewModel: function (name, templateConfig, callback) {
//if there is a 'fromUrl' property
if (templateConfig.fromUrl) {
//use import to load the code
import(templateConfig.fromUrl)
.then(module => {
//viewmodel is loaded asynchronous (one time!)
callback( (params, componentInfo) => {
//initialize the viewModel
const model = module.default(
params,
componentInfo)
//I can only return synchronously here:
return model
});
})
}
}
}
我想做的是使用 async/await 来表示它必须在一切解决之前等待:
//ViewModel is loaded asynchronous (one time!)
callback(async (params, componentInfo) => {
//initialize the viewModel
const model = module.default(
params,
componentInfo)
//I can only return synchronously here:
return await model
});
但是我的 ViewModel 最终成为了 Promise 对象。 关于如何实现这一点的任何建议?
【问题讨论】:
标签: javascript asynchronous knockout.js components knockout-3.0