onload异步改同步
function loadingFile(componentItem){
return new Promise((resolve, reject) => {
let script = ''
const { name, js } = componentItem
if(!window[name]){
script = document.createElement('script')
script.src = js
document.body.appendChild(script)
script.onload = () => {
if(window[name]){
Vue.component(name, window[name].Component)
resolve(window[name].config)
}
}
}
})
}
环语句中使用async/await
export default async function loadingComponents(components) {
const basicConfig = []
let itemConfig
await Promise.all(components.map(async(componentItem) =>{
basicConfig.push(await loadingFile(componentItem))
}))
}
Promise.all()方法只适合所有异步操作都成功的情况,如果有一个操作失败,就无法满足要求。
在使用过程中发现,循环语句使用async/await,如果还需要等待后端接口返回数据和原来的数据进行一一匹配的时候,不能采用以上方式,需要采用以下写法:
const promises = selectComponents.map(async(componentItem) =>{
loadingRes = await loadingFile(componentItem)
})
await Promise.all(promises).then(components => {
// console.log('components', components)
}).catch(e => console.log(e))