node.js – Improving Async/Await Javascript Code


In ES6, when you have a variable that’s going to be used as a property of an object, you can use the same variable name as the property so as to use shorthand syntax, if you want:

const data = await readStream(filteredStream); //Reads in a sample of data and closes the connection. 
return { data };

You do:

filteredStream = streamConnect();

You are assigning to an outer variable named filteredStream. Do you declare and use filteredStream elsewhere? If not, then this is a bug – you’re either implicitly creating a property on the global object, or (if you enable strict mode), an error will be thrown. Always declare variables before using them. You might have wanted to do:

async function readFilteredStream() {
    const filteredStream = streamConnect(); //Connects to API
    const data = await readStream(filteredStream); //Reads in a sample of data and closes the connection. 
    return { data };
}

The respondWithSamples function doesn’t do anything useful. It calls readFilteredStream and returns it. It would be easier and make more sense to just use readFilteredStream instead, and remove respondWithSamples – all you’re doing is creating another wrapper around the Promise, one which will be resolved wherever the Promise is unwrapped.