Skip to content

CasperPromise & Events

Vsevolod Trofimov edited this page Jul 4, 2018 · 11 revisions

Table of contentes

CasperPromise

Methods of casperapi instance return a Promise extended with an event system, to keep things simple for most use cases and support new language features like async\await.
Events are mostly useful for tracking progress. They can be used like

casper.getFile(uuid)
      .on('progress', done => console.log('download progress', done))
      .then(data => { /* do something with the downloaded file */ })

progress

Description

Fires each time chunk of data was uploaded \ downloaded.
This event is only available for casper.save and casper.getFile.

Callback args
  1. Nubmer Indication of how much data was transferred on a scale from 0 (nothing) to 1 (whole file, which means that operation was completed)
Example
casper.getFile(uuid)
      .on('progress', done => console.log('download progress', done))
      .then(data => { /* do something with the downloaded file */ })

sc-connected

Description

Fires when web3 has received the response from the smart contract. Only fires once.
This event is available for all methods.

Callback args

none

Example
casper.save(new Buffer.from('something'))
      .on('sc-connected', () => console.log('got necessary data from smart contract'))

node-found

Description

Fires when some node has responded to the request, can fire multiple times. Last result has node on which operation has completed successfully.
This event is available for all methods.

Callback args
  1. String Node's ip address.
Example
casper.save(new Buffer.from('something'))
      .on('node-found', ip => console.log('uploading to', ip))

Usage & Caveats

Events can be chained, but .on should be called on initial promise.

// this works
casper.getFile(uuid)
      .on('node-found', ip => console.log('uploading to', ip))
      .on('progress', done => console.log('download progress', done))
      .then(() => console.log('done'))


// this works
const getPromise = casper.getFile(uuid)
getPromise.then(() => console.log('done'))
getPromise
      .on('node-found', ip => console.log('uploading to', ip))
      .on('progress', done => console.log('download progress', done))


// this works
const get = async () => {
   const file = await casper.getFile(uuid)
                            .on('progress', done => console.log('download progress', done))
   return file
}

// this doesn't
casper.getFile(uuid).then(() => console.log('done'))
                    .on('progress', done => console.log('download progress', done))

Clone this wiki locally