我有一个 HttpClient 服务,负责处理所有其余调用。 现在,在进行休息调用之前,我想加载一个 iframe,然后继续相同的函数调用。
public get(url, searchParams: URLSearchParams = new URLSearchParams(), headers: Headers = new Headers() ) {
if (some condition) {
let iframe = this.createIframe();
return new Promise((resolve) =>
setTimeout(() => {
iframe.parentNode.removeChild(iframe);
resolve(this.doGET(url, this.getOptions(searchParams, headers)));
}, this.time_delay));
} else {
return this.doGET(url, this.getOptions(searchParams, headers));
}
}
这是 createIframe 方法:
private createIframe() {
let iframe = document.createElement('iframe');
iframe.style.display = 'none';
this.createSomeUrl('').then(function (url) {
iframe.src = url;
});
document.body.appendChild(iframe);
return iframe;
}
在这里,我使用 setTimeout
让 doGet()
调用等待一段时间,但它并不能保证 iframe
是完成它的工作。
有一个变量会在iframe
完成其工作时更新,我可以通过检查该变量知道iframe
已完成其工作,但是到那时如何停止 get 方法等待返回 Promise?
最佳答案
已编辑
private checkSomeConditions(): Promise {
return new Promise( resolve => {
if (some condition) {
let iframe = this.createIframe();
// Assuming the iframe is closing after the job is done
iframe.onbeforeunload( _ => {
console.log('iframe is closing');
resolve();
});
} else resolve();
});
}
public get(url, searchParams: URLSearchParams = new URLSearchParams(), headers: Headers = new Headers() ) {
return this.checkSomeConditions()
.then( _ -> {
return this.doGET(url, this.getOptions(searchParams, headers);
})
[...]
}
关于javascript - 如何在返回值之前等待其他事件完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44842978/