-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolling-to-frontend.js
63 lines (59 loc) · 1.56 KB
/
polling-to-frontend.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const axios = require('axios');
const tryToConnect = async ({ url, method = 'get'}) => {
const result = await axios({
url,
method,
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
})
.then(res => {
// console.log(res.toJSON());
return Promise.resolve();
})
.catch(err => {
// console.log(err.toJSON());
return Promise.reject();
});
return result;
};
const myTimeoutPromise = ms => new Promise((res, rej) => {
// something could be checked...
if (true) { setTimeout(res, ms); } else { }
});
function createPollingByConditions (props) {
const {
url,
method,
toBeOrNotToBe,
interval,
callbackAsResolve,
callbackAsReject
} = props
// console.log ("createPollingByConditions ()", url, toBeOrNotToBe(), interval);
if (toBeOrNotToBe()) {
tryToConnect({ url, method })
.then (
result => {
console.log ('createPollingByConditions () is done.')
callbackAsResolve(result)
return myTimeoutPromise(interval)
},
err => {
callbackAsReject('createPollingByConditions () is failed: Trying to reconnect...')
return (myTimeoutPromise (interval))
}
)
.then (() => {
// this was promised by _devay () which was called at the end of previous then ()
createPollingByConditions (props)
})
.catch (err => {
console.log(err)
createPollingByConditions (props)
});
}
};
module.exports = {
createPollingByConditions
};