Getting started

The simplest distributed job

This is a tutorial for an app that squares an array of numbers uses DCP in Node.js.

In reality, it wouldn’t make sense to put something this computationally cheap on DCP, so the tutorial’s purpose is to provide an example to show how straightforward using DCP is. Please look into more in depth tutorials later for more involved use cases.

Also, if you want to follow along, first create an account and set up your keystore following this tutorial.

Enter this into your terminal to download the DCP packages. Then create a file to write your JavaScript code in.

npm i dcp-client

Require the necessary client DCP packages.

const { init } = require('dcp-client');

await init('https://scheduler.distributed.computer');
const compute = require('dcp/compute');

These are the numbers to square which is the input set to distribute.

const data = [1, 53, 2, 12];

This is the work function that squares each element of the input set. The DCP sends the function out to several Workers with one element of the input set.

function workFunction(datum) {
  // Return the square of the number passed in
  progress();
  return datum * datum;
}

This creates a job and deploys it on the network where workers execute it remotely. It waits for the results to come back from the job.exec() call and then prints them to the terminal.

This creates a job object made up of the array of numbers and work function defined earlier. The job.exec() function splits the job into pieces and send each piece to a worker to compute. After waiting for the results to come back, they’re printed to the console.

const job = compute.for(data, workFunction);
const results = await job.exec();
console.log(results);

Here is the full code:

async function main() {
  const { init } = require('dcp-client');
  await init('https://scheduler.distributed.computer');
  const compute = require('dcp/compute');

  // Data and work function
  const data = [1, 53, 2, 12];
  function workFunction(datum) {
    // Return the square of the number passed in
    progress();
    return datum * datum;
  }

  // Create and execute the job
  const job = compute.for(data, workFunction);
  const results = await job.exec();
  console.log(Array.from(results));
}
main();

Congrats, you’ve distributed code and data across remote computers to perform parallel calculations.