我正在尝试确定一种方法来“暂停”我的 Promises 代码,直到条件成立为止,也许可以使用递归setTimeout()
。对于我的简单示例,我手动设置waitValue
.
我需要等一下,如果waitValue
仍然是错误的,那就只能继续等待了。当然,当waitValue
为真,则继续处理。这是我到目前为止拼凑的内容:
var counter=0;
function promiseTest() {
return new Promise( (resolve, reject) => {
if ( waitValue ) {
console.log('waitValue is now true');
resolve('FIRST PROMISE');
} else { // we need to wait again
if ( counter > 1000 ) { // dont wait forever.
reject('waited too long');
} else {
console.log('WAIT MESSAGE: ' + counter++ );
setTimeout( promiseTest, 3000);
}
}
})
.then( result => {
return(`SECOND PROMISE: the result is: ${result}`);
});
}
并使用它:
promiseTest().then( (result)=>{ console.log('LOCAL MESSAGE: ' + result); });
以下工作正常:
var waitValue = true;
promiseTest().then( (result)=>{ console.log('LOCAL MESSAGE: ' + result); });
// waitValue is now true
// LOCAL MESSAGE: SECOND PROMISE: the result is: FIRST PROMISE
但是,以下内容似乎没有按照我想要的方式完成:
var waitValue = false;
promiseTest().then( (result)=>{ console.log('LOCAL MESSAGE: ' + result); });
// waiting messages appear as expected
waitValue = true;
// waitValue is now true
// no other messages
我一直无法找到暂时执行的承诺示例。一个普通的 JavaScript 示例可能如下所示:
var waitValue = false;
var counter = 0;
(function tester() {
if ( waitValue ) {
console.log('finally true');
} else {
if ( counter > 1000 ) {
console.log('waited too long');
process.exit;
} else {
console.log('still waiting, counter = ' + counter++);
setTimeout(tester, 1000);
}
}
})();
// wait a few seconds and enter this into the console:
var waitValue = false;
暂时暂停执行的 Promise 脚本会是什么样子?或者也许 Promise 根本不应该这样使用?
非常感谢。