node.js - JavaScript Polling until getting specific result? -
i trying add polling application using link https://davidwalsh.name/javascript-polling (and many others).
i have access following implemented api:
client.get('url') // returns promise result of getting result url // application working on, // url returns json looks following // {status: done or in progress, other values...} // when status done other values use in application client.post('url', {data: passanydatahere}) // sends post request result of sending data url // starts specific job
one of problems have run while trying adapt javascript polling code linked above, when find out status done, have no way of returning result outside of promise. can give me tips on how this? (polling until find specific value, , return value use later)
let me give example
export default function somefunction() { let = client.get('/status'); a.then( dataresult => { if (dataresult.status == "done") { //** want other values in dataresult here // , store somewhere else use later } }); // ***want work results here. // need way status of happened inside .then(..) part // have return success or failure , results frontend // (this part done) }
the base of code 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!
also, application working on not use jquery.
one option alter poll
function resolve when required conditions have been met:
function poll(pollfn, interval = 100) { var intervalhandle = null return { until(conditionfn) { return new promise((resolve, reject) => { intervalhandle = setinterval(() => { pollfn().then((data) => { let passescondition = false; try { passescondition = conditionfn(data); } catch(e) { reject(e); } if (passescondition) { resolve(data); clearinterval(intervalhandle); } }).catch(reject) }, interval) }) } } } var counter = 0; function getstatus() { if (counter++ === 5) { return promise.resolve({ status: 'done', otherstuff: 'hi' }); } console.log('not done, keep going') return promise.resolve({ status: 'working' }); } poll(getstatus, 500) .until(data => data.status === 'done') .then((data) => { // data console.log('status done', data) })
Comments
Post a Comment