我有一个功能:
fn = () => {
fn1(); // call first
fn2(); // call only when listener is done from fn1
}
和这两个fns:
fn1 = () => {
const k1 = new Image();
k1.src = someSrc;
k1.addEventListener('load', () => some func {});
}
我的问题:仅当调用fn2
并触发加载事件时,如何使fn1
函数才能启动?
const fn = async () => {
await fn1(); // call first
await fn2(); // call only when listener is done from fn1
}
const fn1 = async () => {
const k1 = new Image();
k1.src = await 'https://www.medicalnewstoday.com/content/images/articles/326/326253/corgi-and-terrier-running.jpg';
await k1.addEventListener('load', async () => await console.log('it should log first'));
}
const fn2 = async () => {
console.log('then second');
}
fn();
答案 0 :(得分:4)
如果要使用async / await(如注释中所述),则需要创建并返回Promise:
const fn1 = () => {
return new Promise((resolve) => {
const k1 = new Image();
k1.src = someSrc;
k1.addEventListener('load', resolve);
});
}
然后您可以在异步函数中等待此承诺:
const fn = async () => {
await fn1();
fn2();
}
答案 1 :(得分:1)
尝试这样的事情:
const fn1 = () => {
const k1 = new Image();
k1.src = 'https://www.medicalnewstoday.com/content/images/articles/326/326253/corgi-and-terrier-running.jpg';
document.body.appendChild(k1);
return new Promise(resolve => {
k1.addEventListener('load', () => resolve('I am done!'));
})
}
const fn2 = () => {
console.log('then second');
}
const fn = async () => {
const a = await fn1(); // call first
console.log(a);
fn2(); // call only when listener is done from fn1
}
fn();