Search code examples
javascriptpromiseasync-awaitfetch

Fetch request and convert it to JSON in a single line


I have this piece of code that I would like to refactor:

import handler from "./libs/handler.js";
import fetch from "node-fetch";
async function checkResponseStatus(res) {
    if(res.status >= 400) {
        throw new Error(await res.text());
    } else {
        return res;
    }
}
export const lambda = handler(async (event, context) => {
    const api = process.env.IEXSandbox ? "sandbox" : "cloud";
    const ticker = event.ticker.toLowerCase();
    const token = process.env.IEXPublishableToken;
    const version = process.env.IEXVersion;
    const req = `https://${api}.iexapis.com/${version}/stock/${ticker}/quote?token=${token}`;
    const res = await fetch(req).then(checkResponseStatus);
    return await res.json();
});

It's essentially a fetch into a 3rd party API, namely IEXCloud, it works fine and does its job. However, I would like to do some work on the response before returning it, so I can simply do this instead:

const res = await fetch(req).then(checkResponseStatus);
const x = await res.json();
return x.companyName;

However, I feel like this is pretty clunky. I would like to know if I can only define a single object instead of having both res and x. This can be done my way, but I want to know for learning purposes. Thank you for reading!


Solution

  • You can try instead of a new variable called x to catch in a then() like this:

    const res = await fetch(req)
        .then(checkResponseStatus)
        .then(res => res.json());