3 回答
TA贡献1818条经验 获得超7个赞
不改变就无法实现你想要的doSomethingAsync
。该函数立即完成并且无法检测何时setTimeout
完成。除非你能找到一些其他的副作用来监测,否则你就不走运了。
从技术上讲,在doSomethingAsync
完成执行后立即执行某些操作很容易。它几乎立即完成。您不能做的是在setTimeout
触发器之后执行某些操作。因为doSomethingAsync
不会返回与其内部所做的任何联系。
TA贡献1824条经验 获得超6个赞
您似乎正在寻找await关键字。
async function waitForMe() {
console.log("I take time to execute")
}
async function waitsForOthers() {
console.log("I am going to print right now")
await waitForMe() //***
console.log("Now that that's done, I am going to print")
}
TA贡献1783条经验 获得超4个赞
您可以将上述功能更改为,
var doSomethingAsync = () => {
setTimeout(() => {
console.log("do Something Async");
youWantToExecuteAtLast();
}, 1000);
};
// do something after doSomethingAsync has been executed ...
function youWantToExecuteAtLast() {
alert("This is the end");
};
doSomethingAsync();
对于多次调用,
var counter = 0;
var doSomethingAsync = (timer) => {
setTimeout(() => {
console.log("do Something Async : ",(counter+1));
counter++;
youWantToExecuteAtLast();
}, timer);
};
// do something after doSomethingAsync has been executed ...
function youWantToExecuteAtLast() {
if(counter === 3)
alert("Three calls are done");
};
doSomethingAsync(2000);
doSomethingAsync(4000);
doSomethingAsync(6000);
添加回答
举报