项目作者: InterAl

项目描述 :
Wait until a condition is satisfied
高级语言: JavaScript
项目地址: git://github.com/InterAl/wait-for-cond.git
创建时间: 2017-02-21T10:29:06Z
项目社区:https://github.com/InterAl/wait-for-cond

开源协议:

下载


wait-for-cond

Wait until a condition is satisfied. Useful for testing.

Installation

  1. $ npm i -S wait-for-cond

Usage

The promise resolves if the condition is met at least once in the specified duration, and rejects otherwise.

  1. var waitFor = require('wait-for-cond');
  2. var someCondition = true;
  3. waitFor(function() {
  4. return someCondition;
  5. }, 2000, 'an optional reject message')
  6. .then(function() {
  7. console.log('condition is fulfilled.');
  8. })
  9. .catch(function() {
  10. console.error('condition was not fulfilled in time.');
  11. });

The condition result can also be wrapped in a promise.

  1. var waitFor = require('wait-for-cond');
  2. var someCondition = true;
  3. waitFor(function() {
  4. return new Promise(function(resolve) {
  5. return resolve(someCondition);
  6. });
  7. }, 2000, 'an optional reject message')
  8. .then(function() {
  9. console.log('condition is fulfilled.');
  10. })
  11. .catch(function() {
  12. console.error('condition was not fulfilled in time.');
  13. });

waitFor.hold resolves if the condition remains satisfied for the entire duration, and rejects otherwise.

  1. var waitFor = require('wait-for-cond');
  2. var someCondition = true;
  3. waitFor.hold(function() {
  4. return new Promise(function(resolve) {
  5. return someCondition;
  6. });
  7. }, 2000, 'an optional reject message')
  8. .then(function() {
  9. console.log('condition remained satisfied for 2000ms');
  10. })
  11. .catch(function() {
  12. console.error('condition was unsatisfied during the 2000ms duration');
  13. });

Eventual assertions

The promise resolves if the assertion was fulfilled at least once in the specified duration, and rejects otherwise.

  1. var assert = require('assert');
  2. var waitFor = require('wait-for-cond');
  3. var someCondition = true;
  4. waitFor.assert(function() {
  5. assert(someCondition);
  6. }, 2000)
  7. .then(function() {
  8. console.log('assertion succeeded in time.');
  9. })
  10. .catch(function() {
  11. console.log('assertion did not succeed in time.');
  12. });

Eventual holding assertions

The promise resolves if the assertion remains fulfilled for the entire specified duration, and rejects otherwise.

  1. var assert = require('assert');
  2. var waitFor = require('wait-for-cond');
  3. var someCondition = true;
  4. waitFor.assertHold(function() {
  5. assert(someCondition);
  6. }, 2000)
  7. .then(function() {
  8. console.log('assertion was held for the entire duration.');
  9. })
  10. .catch(function() {
  11. console.log('assertion failed in the specified duration.');
  12. });