Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

I would like to know if I can only define a single object instead of having both res and x. Is that possible?

like image 735
Whiteclaws Avatar asked Oct 16 '25 13:10

Whiteclaws


1 Answers

You can also nested async await syntax on ECMAScript 2017 like this:

const data = await (await fetch('api/route')).json();
like image 118
LudacrisX1 Avatar answered Oct 19 '25 08:10

LudacrisX1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!