我有以下代码,使用p-wait-for轮询http端点
const pWaitFor = require('p-wait-for');
const rp = require('request-promise-native');
const options = {
method: 'GET',
simple: false,
resolveWithFullResponse: true,
url: 'https://httpbin.org/json1'
};
const waitOpts = {interval: 15};
(async () => {
await pWaitFor(rp(options), waitOpts);
console.log('done calling');
})();
我收到了错误
(node:36125) UnhandledPromiseRejectionWarning: TypeError: Expected condition to return a boolean
at Promise.resolve.then.then.value (node_modules/p-wait-for/index.js:16:13)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
at Function.Module.runMain (module.js:695:11)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
(node:36125) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:36125) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
目的是每15秒继续轮询https://httpbin.org/json1端点。它应该无限期地继续运行,因为它返回404,请求 - 承诺变成被拒绝的承诺。
通过调用函数返回boolean(true / false),我能够使它工作
const pWaitFor = require('p-wait-for');
const rp = require('request-promise-native');
const options = {
method: 'GET',
simple: false,
resolveWithFullResponse: true,
url: 'https://httpbin.org/json1'
};
const waitOpts = {interval: 1000};
const invokeApi = async () => {
const res = await rp(options);
if (res.statusCode === 200) {
return true;
} else {
return false;
}
};
(async () => {
await pWaitFor(invokeApi, waitOpts);
})();
p-wait-for
预计会返回boolean
(正如您所发现的那样)。
一个比你的answer更好的版本也可以处理任何意外错误,还有4xx
和5xx
状态代码,见下文:
const pWaitFor = require('p-wait-for');
const rp = require('request-promise-native');
const options = {
method: 'GET',
simple: false,
resolveWithFullResponse: true,
url: 'https://httpbin.org/json1'
};
const waitOpts = {interval: 1000};
const invokeApi = async () => {
try {
await rp(options);
return true;
} catch (_) {
// non 200 http status
return false
}
};
(async () => {
await pWaitFor(invokeApi, waitOpts);
})();