lundi 16 août 2021

How to use if / else statement with a JSON fetch API response Javascript

I have two working code snippets that I would like to link with if/else logic. The first part of the code receives a JSON response from a web API. JSON.TEMPERATURE is the key variable needed.

const fetch = require("node-fetch");

const api_url = 'https://www.placeholder_URL.com/api/getTemperature'

fetch(api_url)
  .then((response) => {
    return response.json();
  })
  .then((myJSON) => {
    console.log(myJSON.TEMPERATURE); // **This returns a number between 8 and 15**
  });

The second part of the code plays a MIDI note. In the case below, note # 60 which is the Middle C. C# would be note 61, D note 62 and so forth.

let easymidi = require("easymidi")
let output = new easymidi.Output("mindiPort", true)

let sendNote = (noteValue, duration) => {
    output.send("noteon", noteValue)

    setTimeout(()=> {
        output.send("noteoff", noteValue)
    }, duration);
}

setInterval(() => {
    let noteValue = {
        note: 60,   // **need to change this number depending on JSON.TEMPERATURE**
        velocity: 100,
        channel: 1
    }
    sendNote(noteValue, 500)
}, 2000);

What I am looking to achieve is an if/else where the note played is dependent on JSON.TEMPERATURE.

Something like:

if JSON.TEMPERATURE == 8, play note 60

if JSON.TEMPERATURE == 9, play note 61

else, play note 55

I would also like to run the API request every 5 seconds.

Aucun commentaire:

Enregistrer un commentaire