How to use _hasContext method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

kew.js

Source: kew.js Github

copy
1/**
2 * An object representing a "promise" for a future value
3 *
4 * @param {function(Object)} onSuccess a function to handle successful
5 *     resolution of this promise
6 * @param {function(Error)} onFail a function to handle failed
7 *     resolution of this promise
8 * @constructor
9 */
10function Promise(onSuccess, onFail) {
11  this.promise = this
12  this._isPromise = true
13  this._successFn = onSuccess
14  this._failFn = onFail
15  this._hasContext = false
16  this._nextContext = undefined
17  this._currentContext = undefined
18}
19
20/**
21 * Specify that the current promise should have a specified context
22 * @param  {Object} context context
23 */
24Promise.prototype._useContext = function (context) {
25  this._nextContext = this._currentContext = context
26  this._hasContext = true
27  return this
28}
29
30Promise.prototype.clearContext = function () {
31  this._hasContext = false
32  this._nextContext = undefined
33  return this
34}
35
36/**
37 * Set the context for all promise handlers to follow
38 * @param {context} context An arbitrary context
39 */
40Promise.prototype.setContext = function (context) {
41  this._nextContext = context
42  this._hasContext = true
43  return this
44}
45
46/**
47 * Get the context for a promise
48 * @return {Object} the context set by setContext
49 */
50Promise.prototype.getContext = function () {
51  return this._nextContext
52}
53
54/**
55 * Resolve this promise with a specified value
56 *
57 * @param {Object} data
58 */
59Promise.prototype.resolve = function (data) {
60  if (this._error || this._hasData) throw new Error("Unable to resolve or reject the same promise twice")
61
62  var i
63  if (data && data._isPromise) {
64    this._child = data
65    if (this._promises) {
66      for (var i = 0; i < this._promises.length; i += 1) {
67        data._chainPromise(this._promises[i])
68      }
69      delete this._promises
70    }
71
72    if (this._onComplete) {
73      for (var i = 0; i < this._onComplete.length; i+= 1) {
74        data.fin(this._onComplete[i])
75      }
76      delete this._onComplete
77    }
78    return
79  }
80
81  this._hasData = true
82  this._data = data
83
84  if (this._onComplete) {
85    for (i = 0; i < this._onComplete.length; i++) {
86      this._onComplete[i]()
87    }
88  }
89
90  if (this._promises) {
91    for (i = 0; i < this._promises.length; i += 1) {
92      this._promises[i]._withInput(data)
93    }
94    delete this._promises
95  }
96}
97
98/**
99 * Reject this promise with an error
100 *
101 * @param {Error} e
102 */
103Promise.prototype.reject = function (e) {
104  if (this._error || this._hasData) throw new Error("Unable to resolve or reject the same promise twice")
105
106  var i
107  this._error = e
108
109  if (this._ended) {
110    process.nextTick(function onPromiseThrow() {
111      throw e
112    })
113  }
114
115  if (this._onComplete) {
116    for (i = 0; i < this._onComplete.length; i++) {
117      this._onComplete[i]()
118    }
119  }
120
121  if (this._promises) {
122    for (i = 0; i < this._promises.length; i += 1) {
123      this._promises[i]._withError(e)
124    }
125    delete this._promises
126  }
127}
128
129/**
130 * Provide a callback to be called whenever this promise successfully
131 * resolves. Allows for an optional second callback to handle the failure
132 * case.
133 *
134 * @param {function(Object)} onSuccess
135 * @param {?function(Error)} onFail
136 * @return {Promise} returns a new promise with the output of the onSuccess or
137 *     onFail handler
138 */
139Promise.prototype.then = function (onSuccess, onFail) {
140  var promise = new Promise(onSuccess, onFail)
141  if (this._nextContext) promise._useContext(this._nextContext)
142
143  if (this._child) this._child._chainPromise(promise)
144  else this._chainPromise(promise)
145
146  return promise
147}
148
149/**
150 * Provide a callback to be called whenever this promise is rejected
151 *
152 * @param {function(Error)} onFail
153 * @return {Promise} returns a new promise with the output of the onFail handler
154 */
155Promise.prototype.fail = function (onFail) {
156  return this.then(null, onFail)
157}
158
159/**
160 * Provide a callback to be called whenever this promise is either resolved
161 * or rejected.
162 *
163 * @param {function()} onComplete
164 * @return {Promise} returns the current promise
165 */
166Promise.prototype.fin = function (onComplete) {
167  if (this._hasData || this._error) {
168    onComplete()
169    return this
170  }
171
172  if (this._child) {
173    this._child.fin(onComplete)
174  } else {
175    if (!this._onComplete) this._onComplete = [onComplete]
176    else this._onComplete.push(onComplete)
177  }
178
179  return this
180}
181
182/**
183 * Mark this promise as "ended". If the promise is rejected, this will throw an
184 * error in whatever scope it happens to be in
185 *
186 * @return {Promise} returns the current promise
187 */
188Promise.prototype.end = function () {
189  if (this._error) {
190    throw this._error
191  }
192  this._ended = true
193  return this
194}
195
196/**
197 * Attempt to resolve this promise with the specified input
198 *
199 * @param {Object} data the input
200 */
201Promise.prototype._withInput = function (data) {
202  if (this._successFn) {
203    try {
204      this.resolve(this._successFn(data, this._currentContext))
205    } catch (e) {
206      this.reject(e)
207    }
208  } else this.resolve(data)
209
210  // context is no longer needed
211  delete this._currentContext
212}
213
214/**
215 * Attempt to reject this promise with the specified error
216 *
217 * @param {Error} e
218 */
219Promise.prototype._withError = function (e) {
220  if (this._failFn) {
221    try {
222      this.resolve(this._failFn(e, this._currentContext))
223    } catch (e) {
224      this.reject(e)
225    }
226  } else this.reject(e)
227
228  // context is no longer needed
229  delete this._currentContext
230}
231
232/**
233 * Chain a promise to the current promise
234 *
235 * @param {Promise} the promise to chain
236 */
237Promise.prototype._chainPromise = function (promise) {
238  var i
239  if (this._hasContext) promise._useContext(this._nextContext)
240
241  if (this._child) {
242    this._child._chainPromise(promise)
243  } else if (this._hasData) {
244    promise._withInput(this._data)
245  } else if (this._error) {
246    promise._withError(this._error)
247  } else if (!this._promises) {
248    this._promises = [promise]
249  } else {
250    this._promises.push(promise)
251  }
252}
253
254/**
255 * Utility function used for creating a node-style resolver
256 * for deferreds
257 *
258 * @param {Promise} deferred a promise that looks like a deferred
259 * @param {Error} err an optional error
260 * @param {Object} data optional data
261 */
262function resolver(deferred, err, data) {
263  if (err) deferred.reject(err)
264  else deferred.resolve(data)
265}
266
267/**
268 * Creates a node-style resolver for a deferred by wrapping
269 * resolver()
270 *
271 * @return {function(Error, Object)} node-style callback
272 */
273Promise.prototype.makeNodeResolver = function () {
274  return resolver.bind(null, this)
275}
276
277/**
278 * Static function which creates and resolves a promise immediately
279 *
280 * @param {Object} data data to resolve the promise with
281 * @return {Promise}
282 */
283function resolve(data) {
284  var promise = new Promise()
285  promise.resolve(data)
286  return promise
287}
288
289/**
290 * Static function which creates and rejects a promise immediately
291 *
292 * @param {Error} e error to reject the promise with
293 * @return {Promise}
294 */
295function reject(e) {
296  var promise = new Promise()
297  promise.reject(e)
298  return promise
299}
300
301/**
302 * Replace an element in an array with a new value. Used by .all() to
303 * call from .then()
304 *
305 * @param {Array.<Object>} arr
306 * @param {number} idx
307 * @param {Object} val
308 * @return {Object} the val that's being injected into the array
309 */
310function replaceEl(arr, idx, val) {
311  arr[idx] = val
312  return val
313}
314
315/**
316 * Takes in an array of promises or literals and returns a promise which returns
317 * an array of values when all have resolved. If any fail, the promise fails.
318 *
319 * @param {Array.<Promise|Object>} promises
320 * @return {Promise.<Array.<Object>>}
321 */
322function all(promises) {
323  if (arguments.length != 1 || !Array.isArray(promises)) {
324    promises = Array.prototype.slice.call(arguments, 0)
325  }
326  if (!promises.length) return resolve([])
327
328  var outputs = []
329  var counter = 0
330  var finished = false
331  var promise = new Promise()
332  var counter = promises.length
333
334  for (var i = 0; i < promises.length; i += 1) {
335    if (!promises[i] || !promises[i]._isPromise) {
336      outputs[i] = promises[i]
337      counter -= 1
338    } else {
339      promises[i].then(replaceEl.bind(null, outputs, i))
340      .then(function decrementAllCounter() {
341        counter--
342        if (!finished && counter === 0) {
343          finished = true
344          promise.resolve(outputs)
345        }
346      }, function onAllError(e) {
347        if (!finished) {
348          finished = true
349          promise.reject(e)
350        }
351      })
352    }
353  }
354
355  if (counter === 0 && !finished) {
356    finished = true
357    promise.resolve(outputs)
358  }
359
360  return promise
361}
362
363/**
364 * Create a new Promise which looks like a deferred
365 *
366 * @return {Promise}
367 */
368function defer() {
369  return new Promise()
370}
371
372/**
373 * Return a promise which will wait a specified number of ms to resolve
374 *
375 * @param {number} delayMs
376 * @param {Object} returnVal
377 * @return {Promise.<Object>} returns returnVal
378 */
379function delay(delayMs, returnVal) {
380  var defer = new Promise()
381  setTimeout(function onDelay() {
382    defer.resolve(returnVal)
383  }, delayMs)
384  return defer
385}
386
387/**
388 * Return a promise which will evaluate the function fn with the provided args
389 *
390 * @param {function} fn
391 * @param {Object} var_args a variable number of arguments
392 * @return {Promise}
393 */
394function fcall(fn, var_args) {
395  var defer = new Promise()
396  defer.resolve(fn.apply(null, Array.prototype.slice.call(arguments, 1)))
397  return defer
398}
399
400/**
401 * Binds a function to a scope with an optional number of curried arguments. Attaches
402 * a node style callback as the last argument and returns a promise
403 *
404 * @param {function} fn
405 * @param {Object} scope
406 * @param {Object} var_args a variable number of arguments
407 * @return {Promise}
408 */
409function bindPromise(fn, scope, var_args) {
410  var rootArgs = Array.prototype.slice.call(arguments, 2)
411  return function onBoundPromise(var_args) {
412    var defer = new Promise()
413    fn.apply(scope, rootArgs.concat(Array.prototype.slice.call(arguments, 0), defer.makeNodeResolver()))
414    return defer
415  }
416}
417
418module.exports = {
419    all: all
420  , bindPromise: bindPromise
421  , defer: defer
422  , delay: delay
423  , fcall: fcall
424  , resolve: resolve
425  , reject: reject
426}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Puppeteer on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)