使用p-wait-轮询http端点以返回UnhandledPromiseRejectionWarning:TypeError:预期条件返回布尔值

时间:2018-09-07 14:27:07

标签: node.js es6-promise polling

我有以下代码使用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,而请求承诺变成了拒绝的诺言。

2 个答案:

答案 0 :(得分:0)

我能够通过调用函数返回布尔值(真/假)来使其工作

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);
})();

答案 1 :(得分:0)

p-wait-for期望返回boolean的值(如您所知)。

比您的answer更好的版本也可以处理任何意外的错误,还可以处理4xx5xx状态码,如下所示:

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);
})();