3
\$\begingroup\$

I'm working on a data analytics dashboard in Node.js as a portfolio piece. I've built a pipeline that gets the data where it needs to be for more processing, however, I feel the below code can be improved but it overlaps with my inexperience with Node.js and async/await.

The below code looks redundant to my eye. I tried to move the second function into the first in an anonymous async function to no avail, and was wondering if the more experience members here had any suggestions?

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

async function respondWithSamples() {
    const results = await readFilteredStream();
    return results;
}
\$\endgroup\$
0

2 Answers 2

4
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

I would refactor the second function to simply:

const readFilteredStream = ()=> streamConnect().then(readStream)

Imho much more readable.

There's really no point into creating an object with a single key data, it can be done directly on the result of the function call.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.