轮询直到获得特定结果? [英] Polling until getting specific result?

查看:56
本文介绍了轮询直到获得特定结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用此链接 https://davidwalsh.name/javascript-向我的应用程序添加轮询(还有许多其他).

I am currently trying to add polling to my application using this link https://davidwalsh.name/javascript-polling (and many others).

我可以访问以下已实现的api:

I have access to the following already implemented api:

client.get('url')
// returns Promise with result of getting result from url
// for the application I am working on,
//     the URL returns json that looks like the following 
//     {status: DONE or IN PROGRESS, other values...}
// when status is DONE other values are what I will use in the application

client.post('url', {data: passAnyDataHere}) 
// sends a post request with result of sending data to url
// starts the specific job

我遇到的问题之一是,当尝试调整上面链接的JavaScript轮询代码时,当我发现状态为完成"时,我无法将结果返回到Promise之外.有人可以给我提示如何操作吗?(轮询直到找到特定值,然后返回该值以供以后使用)

One of the problems that I have run into is that while trying to adapt the JavaScript Polling code I linked to above, when I find out that the status is DONE, I have no way of returning the result to outside of the Promise. Can someone give me tips on how to do this? (polling until I find a specific value, and then return the value for use later)

让我给你一个例子

export default function someFunction() {
    let a = client.get('/status');
    a.then( dataResult => 
      {
         if (dataResult.status == "DONE") {
            //** want to get other values in dataResult here 
            // and store it somewhere else for use later
         }
      });
    // ***want to work with results here.
    // need some way to get the status of what happened inside the .then(..) part
   //  eventually have to return success or failure and results to the frontend
   // (this part is already done)
 }

代码的基础是 https://github.com/erikras/react-redux-universal-hot-example#server-side-data-fetching (使用React.js/Node.js/Redux/etc.)

The base of the code is https://github.com/erikras/react-redux-universal-hot-example#server-side-data-fetching (uses React.js/Node.js/Redux/etc.)

任何提示/建议/帮助均受到赞赏.谢谢!

Any tips/suggestions/help are/is appreciated. Thanks!

此外,我正在使用的应用程序不使用JQuery.

Also, the application I am working on does not use JQuery.

推荐答案

下面是使用promise和poll直到获得所需结果的函数示例.我还对其进行了参数设置,以便您可以传入轮询间隔和超时值:

Here's an example of a function that uses promises and polls until you get the desired result. I've also parameterized it so that you can pass in the polling interval and a timeout value:

// create a promise that resolves after a short delay
function delay(t) {
    return new Promise(function(resolve) {
        setTimeout(resolve, t);
    });
}

// interval is how often to poll
// timeout is how long to poll waiting for a result (0 means try forever)
// url is the URL to request
function pollUntilDone(url, interval, timeout) {
    let start = Date.now();
    function run() {
        return client.get(url).then(function(dataResult) {
            if (dataResult.status === "DONE") {
                // we know we're done here, return from here whatever you 
                // want the final resolved value of the promise to be
                return dataResult;
            } else {
                if (timeout !== 0 && Date.now() - start > timeout) {
                    throw new Error("timeout error on pollUntilDone");
                } else {
                    // run again with a short delay
                    return delay(interval).then(run);
                }
            }
        });
    }
    return run();
}

// sample usage
// polls every 500ms for up to 30 seconds
pollUntilDone(someUrl, 500, 30 * 1000).then(function(result) {
   // have final result here 
}).catch(function(err) {
    // handle error here
});

这里的关键是链接您的诺言,因此,每次您再次调用 run()时,您都会返回其值,以便将其链接到先前的诺言.然后,每当您最终返回一个值或引发异常时,原始的promise将获得该值或错误作为已解决的值或被拒绝的原因.

The key here is to chain your promises so each time you call run() again, you return its value so it is chained to the prior promise. Then, whenever you finally return a value or throw an exception, the original promise will get that value or error as the resolved value or rejected reason.

请注意,我添加了一个超时,因为您确实永远都不想永远轮询,尤其是在某些不可预见的和经常发生的错误可能不会拒绝承诺但不会为您带来想要的结果的情况下.

Note that I added a timeout because you really never want to be polling forever, particularly in cases where some unforeseen and recurring error might not reject the promise, but won't get you the result you want.

这篇关于轮询直到获得特定结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆