假设我们有一些 Promise,因为我们知道它会在某个时刻解决。现在我有重复调用的同步代码(例如不可能等待)(例如onAnimationFrame)。如果承诺的结果已履行,如何使用那里的结果?
像(JS伪代码):
let promise=FetchSomething();
let updater = ()=>{
drawSomething();
if(promise IS FULLFILLED) // how to know if fullfilled?
drawThing(RESULT OF promise); // how to get the result here?
requestAnimationFrame(updater);
}
updater();
最简单的方法是自己设置一个变量:
let promise = FetchSomething();
let done = false
/* variable will be set once promise settled */
promise.then(() => {
done = true
})
let updater = () => {
drawSomething();
if (done) {
drawThing(/* RESULT OF promise */);
}
requestAnimationFrame(updater);
}
updater();
您可以对结果执行相同的操作,即:
let promise = FetchSomething();
let done = false
let result = null
promise.then((value) => {
done = true
result = value
})
let updater = () => {
drawSomething();
if (done) {
drawThing(result);
}
requestAnimationFrame(updater);
}
updater();