我正在努力在我的程序中做一個簡單的等待功能。如果可能,我想使用promise和async等待。我到目前爲止:Javascript等待條件使用承諾爲真
function waitForCondition(conditionObj) {
var start_time = new Date().getTime()
function checkFlag() {
if (conditionObj.arg == conditionObj.test) {
console.log('met');
return new Promise(resolve => setTimeout(resolve, 1));
} else if (new Date() > start_time + 3000) {
console.log('not met, time out');
return new Promise(resolve => setTimeout(resolve, 1));
} else {
window.setTimeout(checkFlag, 1000);
}
}
checkFlag();
}
async function run() {
console.log('before');
await waitForCondition({arg: '1', test: '1'})
console.log('after');
}
run();
它應該每隔1秒檢查一次,最長時間爲3秒。控制檯應該是這樣的:
'before'
'met'
'after'
是的,但請不要寫那樣的承諾邏輯。你應該promisify'setTimeout',沒有別的。 – Bergi
@petermader謝謝你的驚人答案,這正是我想要做的。 –