Skip to main content

Generators

The simplest way to expose data from your Sequence is by following a generator pattern. Generators provide a powerful and flexible approach to writing asynchronous code.

The generator will create new data item on each function call, exposing this data item on the Sequence output stream. In this example you see the yield keyword is used to expose items obtained from the mock API fetching function.

A useful feature of JavaScript generators is that those can yield* - this means that an iterator or an array can be passed and therefore multiple chunks can be send to the output stream. This is advisable for efficiency reasons.

Generators have one additional benefit: they will not produce more data if data is not read. If you start a generator in your Sequence but not read from it, the program will run a couple initial iterations to fill in the buffers, but eventually it will stop at yield and wait until you read the data. You can read the data generated by the Sequence for example using the Scramjet Instance API.

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function getPageFromApi(){
return "Your result";
}

module.exports = async function* () {
while(true){
yield await getPageFromApi();
await sleep(1000)
}
}

The simplest way to run a generator function in a Sequence is to save the below JSON under the name package.json for it to be packed with the main file as a tar.gz.

Or create a package.json file with the values that you supply, use the command-line npm init -. It creates a new package.json file with elementary properties containing prompts about the project's name, version, etc. More information on the package.json file shown in the illustration below.

{
"name": "@scramjet/js-task",
"version": "1.0.0",
"description": "Scramjet Cloud Platform Sequence Javascript Template",
"main": "index.js",
"scripts": {
"predeploy": "mkdir -p dist/ && cp index.js package.json dist/ && (cd dist && npm i --omit=dev)"
},
"engines": {
"node": ">=16"
},
"repository": {
"type": "git",
"url": "git+https://github.com/scramjetorg/create-sequence.git"
},
"bugs": {
"url": "https://github.com/scramjetorg/create-sequence/issues"
},
"homepage": "https://github.com/scramjetorg/create-sequence#readme"
}
  • Check out Scramjet's Command lines Interface (CLI) section.

  • GitHub logo Visit Scramjet's Sample GitHub repository for more examples of Sequences.


Was it helpful?

Didn't find information needed?

Join our Scramjet Community on Discord, where you can get help from our engineers directly.