let msg = "Done";
function promise() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Done");
}, 2000);
});
}
async function func1() {
msg = "Pending";
console.log("Starting...");
const a = await promise();
console.log(a);
msg = a;
}
async function func2() {
console.log("Queued");
}
async function call() {
if ((msg) === "Done") {
func1();
} else {
func2();
}
}
<h1>PROMISE</h1>
<input onclick="call()" type="button" value="Click me " />
I added this piece of code into func2(), it runs func1() after the previous promise is resolved, but it also runs it immediately after click. How can i do so it only runs after previous promise is resolved.
func2() {
console.log("Queued");
await func1();
func1();
}
EDIT: Guys! I solved this problem using Date().getTime() method, and adding "clicks" variable. The result is almost the same. But the way of doing it is different. When i click its immediately starts executing promise, but i wanted it to wait untill the promise from previous click is finished and only then start executing a new promise. I think there has to be some other simpler solution.
let msg = "Done";
let clicks = 0;
let t1;
let t2;
let timeout = 0;
let txt = "";
function promise() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Done");
}, 2000 * clicks - timeout);
});
}
async function func1() {
clicks = 1;
timeout = 0;
txt = "";
msg = "Pending";
let time = new Date();
t1 = time.getTime();
const a = await promise();
let taym = new Date();
let now = taym.getTime();
createDiv(now, t1, txt);
msg = a;
}
async function func2() {
clicks ;
let time = new Date();
t2 = time.getTime();
timeout = t2 - t1;
const a = await promise();
let taym = new Date();
let now = taym.getTime();
txt = " and " (now - t2) " ms after last click";
createDiv(now, t1, txt);
}
async function call() {
if (msg === "Done") {
func1();
} else {
func2();
}
}
function createDiv(a, b, c) {
let div = document.createElement("div");
div.innerHTML = "Created " (a - b) " ms after main click" c;
document.body.appendChild(div);
}
<h1>PROMISE</h1>
<input onclick="call()" type="button" value="Click me " />
uj5u.com熱心網友回復:
下面的代碼做我認為你想要的
決議事件,只是為了表明第二次點擊中顯示的時間戳是第一次點擊的時間戳,因為這就是這個例子中的承諾決議
不確定這段代碼有多大用處
const promise = new Promise(resolve => {
document.getElementById('bang').addEventListener('click', e => {
console.log('first click');
resolve(e);
}, { once: true });
})
promise.then(e => {
console.log(e.timeStamp, e.type, e.target.id);
document.getElementById('bang').addEventListener('click', e => {
promise.then(e => {
console.log('not the first click');
console.log(e.timeStamp, e.type, e.target.id);
})
})
})
<button id="bang">Resolve the promise</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/456693.html
