根据下面代码实现同步调用:
function getUser() {
return fetch('http://www.baidu.com?123')
}
function m1() {
return getUser()
}
function m2() {
return m1()
}
function m3() {
return m2()
}
function main() {
const user = m3()
console.log(user)
}
解决办法:
function run(func) {
let cache = []
let i = 0
const _originalFetch = window.fetch
window.fetch = (...args) => {
if(cache[i]) {
// 交付缓存结果
if(cache[i].status === 'fulfilled') {
return cache[i].data
}
if(cache[i].status === 'rejected') {
throw cache[i].err
}
}
const result = {
status: 'pending',
data: null,
err: null
}
cache[i++] = result
// 发送请求
const prom = _originalFetch(...args)
.then(resp => resp.json())
.then(res => {
result.status = 'fulfilled'
result.data = res
}, err => {
result.status = 'rejected'
result.err = err
})
// 报错
throw
}
try {
func()
} catch(err) {
if(err instanceof Promise) {
const reRun = () => {
i = 0
run(func)
}
err.then(reRun, reRun)
}
}
}
run(main)