gpt4 book ai didi

javascript - 我怎样才能让 `.then()` 保持足够长的时间以实现具有 native promise 的轮询功能?

转载 作者:数据小太阳 更新时间:2023-10-29 06:10:19 26 4
gpt4 key购买 nike

总结:poll()带有回调的函数可用;我还没有发现任何使用 native promise 。我试图改编一些但没有成功。我还没有解决的问题是,当 setTimeout 调用的函数的第一个实例结束而没有任何返回时, .then()监听它会将终止视为 false和一个 reject() . then()终止并且不监听以后的返回。

问题:如何最好地帮助 .then()函数坚持使用 resolve() 稍后返回或 reject()

这篇文章的其余部分是细节。阅读有帮助的内容。

可用的投票功能:我喜欢 ( https://stackoverflow.com/users/1249219/om-shankar ) Om Shankar 在 Calling a function every 60 seconds 中的回复. David Walsh 的 poll() 非常相似(位于 https://davidwalsh.name/essential-javascript-functions )。两者都使用回调并且运行良好。我发现 poll in javascript其中包括 poll()使用 bluebird -只有 promise 。

这是我尝试使用原生 promises 实现的尝试。

/**
* poll - checks repeatedly whether a condition exists. When the condition
* exists, returns a resolved standard promise. When it has checked
* long enough, returns a rejected standard promise.
* @param {function} fn - a caller-supplied synchronous function that
* detects a condition in the environment. Returns true if the
* condition exists; otherwise false.
* @param {number} timeout - maximum number of milliseconds
* the caller wants to check param fn();
* reject() the promise at the expiration of param timeout.
* @param {number} interval - minimum number of milliseconds between
* calls to param fn(); resolve() the promise when param fn() first
* reports true.
* @return {promise} - resolved when param fn() returns true;
* rejected if param timeout expires without param fn() returning true
*/
function poll(fn, timeout, interval) {
let endTime = Number(new Date()) + (timeout || 2000)
interval = interval || 250
return Promise.resolve *2
.then(() => { *3
(function p(fn, endTime, interval) {
if (fn()) { return Promise.resolve("Condition is satisfied.") } *4
else {
if (Number(new Date()) <= endTime) {) *5
window.setTimout(p, interval, fn, endTime, interval) *6
}
else {
return Promise.reject("Past endTime; condition not satisfied")
}
}
}()) *7
}) *8
}

预期用途:

function waitIsOver() { return (<desired condition exists>) }
poll(waitIsOver, 2000, 250) *1

我认为这是运行的方式(如果我错了请纠正我):在调用 poll() 之后在 *1,我们快速返回一个在 *2 的未决 promise ,以便 poll()知道等待。然后,我们称该 promise 为 then() * 3处的功能。函数p()开始。如果fn() (在外部已知 p()waitIsOver() )在 *4 返回真,我们很好:我们返回 resolve()poll()在 *1 得到它寻求的已解决的 promise 。

然后是不好的部分:如果fn()在 *4 处返回 false,我们在 endTime 中在 *5(这很可能;第一次调用不太可能发生在 endTime 之后),我们使用 setTimeout()在 *6 处要求 JS 在堆栈中做一个注释以实例化另一个 p()interval 之后时间。之后,第一个实例p()终止于 *7。在 *8,then()知道 p()没有返回任何东西而终止,并将条件解释为返回 falsereject() ;与 reject() , promise 已经确定,永远不会改变。但是,interval 到期后,p() 的后继实例开火了。它返回的任何东西都丢失了; promise 已定,then()在不需要的路径上发送执行后已终止。

How do I convert an existing callback API to promises?推荐使用 Promise 构造函数的方法,resolve()打电话callback() , 和 reject()打电话errback .我尝试了该技术,但遇到了与 then() 相同的问题功能在我想要之前结束。我还没有弄清楚如何制作then()像回调函数一样耐心等待。

这提出了问题。再次:

问题:如何最好地帮助 .then()函数坚持稍后从 resolve() 返回或 reject()

最佳答案

How best to help the .then() function stick around for later returns from resolve() or reject()

.then() 处理程序在底层 promise 被解决或拒绝时被调用。在此之前从未调用过它。因此,如果您想在调用 .then() 处理程序时延迟,那么您可以延迟解析或拒绝底层 promise ,直到适当的时间。

从我的评论中您可以看出,很难准确地说出您要完成的目标,因为您不只是描述您要完成的简单目标。

鉴于此,这是我对您要实现的目标的猜测。一个明确的问题可能会在几分钟内得到这样的答案。

如果你只是想重复轮询你的函数直到它返回一个真值或直到超时时间命中,你可以使用标准的 ES6 promies 来做到这一点:

function poll(fn, timeout, interval) {
return new Promise(function(resolve, reject) {
// set timeout timer
var timeoutTimer = setTimeout(function() {
clearInterval(intervalTimer);
reject("Past endTime; condition not satisfied");
}, timeout);

// set polling timer
var intervalTimer = setInterval(function() {
if (fn()) {
clearTimeout(timeoutTimer);
clearInterval(intervalTimer);
resolve("Condition is satisfied");
}
}, interval);
});
}

poll(yourFounction, 5000, 100).then(function(result) {
// succeeded here
}).catch(function(err) {
// timed out here
})

或者,对于 Bluebird promise 库,您可以使用其 .timeout() 方法来执行此操作:

function poll(fn, timeout, interval) {
return new Promise(function(resolve, reject) {
// set polling timer
var intervalTimer = setInterval(function() {
if (fn()) {
clearInterval(intervalTimer);
resolve("Condition is satisfied");
}
}, interval);
}).timeout(timeout, "Past endTime; condition not satisfied");
}

poll(yourFounction, 5000, 100).then(function(result) {
// succeeded here
}).catch(function(err) {
// timed out here
})

请注意,这两个方案都返回一个 promise,然后当 poll() 函数完成时,它们会调用 resolve 或 reject 新的 promise,然后将触发任何 .then () 处理程序被调用。


附言我应该补充一点,这一切都假设您的 fn() 是一个同步函数,它返回一个真值或假值(这就是您的代码似乎假定的)。如果您的 fn() 实际上是一个带有回调或 promise 的异步函数,那么需要将其纳入设计中。在我们编写代码以正确使用它之前,您必须向我们展示该函数的调用约定是什么。

关于javascript - 我怎样才能让 `.then()` 保持足够长的时间以实现具有 native promise 的轮询功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38797983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com