Exploring the depths of async/await within ExpressJS fetch operations

So far, my API-middleware code is functioning properly. I am being cautious to avoid any blocking calls in my express server, which is why I have implemented a function containing asynchronous fetch calls.

I'm wondering if this extra step is necessary at all. Wouldn't the first await statement already unblock my express server?

Below is the code snippet:

var express = require('express')
var router = express.Router()
const asyncMiddleware = require('./utils/asyncMiddleware');

async function fetchDataFromAPI(URL, bodyJson, wpToken) {      
    try {        
        return await fetch(URL, {
            method: "POST",
            credentials: "same-origin",
            headers:  {
                "Authorization": "Bearer " + wpToken,
                "Content-Type": "application/json",
                "Accept": "application/json"
            },
            body: bodyJson
    });
    } catch (error) {       
        return {status:544, error:error};
    }
}

router.post("/registerVendor", asyncMiddleware(async (req, res, next) => {              
    const response = await fetchDataFromAPI(myApiUrl, req.body, 1)
    return res
    .status(response.status)
    .send({ data: response});
}));

module.exports = router

Answer №1

If you're wondering whether it's necessary to place your fetch call within a separate async function, the answer is no, it's not a requirement. While it might be beneficial in some cases, it's not mandatory. Simply awaiting the fetch promise directly will suffice and terminate the synchronous part of your async route callback.

I'm questioning whether the function ("fetchCall" as shown in my code snippet) must be declared as async.

No, there's no strict necessity for it to be asynchronous. It doesn't even have to return a promise since you can await any value. To illustrate, consider the following sequence: A, B, C, D, and E are logged consecutively:

async function bar() {
    console.log("B");
    await 42;
    console.log("D");
}

console.log("A");
bar()
.then(() => {
    console.log("E");
})
.catch(error => {
    console.error(error);
});
console.log("C");

In your specific scenario, it may be advantageous to return a promise. The modified function would look like this:

function fetchData(endpoint, data, token) {      
    return fetch(endpoint, {
        method: "POST",
        credentials: "same-origin",
        headers: {
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        body: data
    })
    .catch(error => ({status:544, error:error}));
}

Nonetheless, the benefit of utilizing async and await lies in enabling the creation of asynchronous code that follows familiar branching and looping patterns typically seen in synchronous programming...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute the authenticate method on every router within the express framework

I just started learning about node.js. I am interested in implementing custom authentication using passport.js on all routers. For reference, I found an example at -> https://github.com/passport/express-4.x-http-bearer-example The code snippet below ...

What is the best way to assign an identifier to a variable in this scenario?

script.js $('a').click(function(){ var page = $(this).attr('href'); $("#content").load(page); return false; }); main.html <nav> <a href="home.html">Home</a> <a href="about.html">About</a> < ...

Stripping quotation marks from CSV information using Javascript

After performing a fetch request using JavaScript, I have converted JSON data into CSV format. datetime","open","high","low","close","volume" "2020-01-28","312.48999","318.39999","312.19000","317.69000","31027981" "2020-01-27","309.89999","311.76001","30 ...

Most effective method for adding JQuery events to dynamically generated buttons

I am dynamically generating Twitter Bootstrap modals based on user actions (Long Story). Sometimes, the user may see up to 100 modals on their screen. Each modal contains 5 dynamic buttons, each serving a different purpose with unique ids. I am using jQue ...

ExpressJS - Efficiently managing multiple pages and pagination

I've been working on implementing a solution for handling multiple pages in a search feature using expressjs, but unfortunately, it doesn't seem to be functioning correctly. I have the root and query parameters set up as follows: /properties/sea ...

What can you tell me about Page Event functionality in Datatables?

Curious question -- I'm currently seeking a practical example of how to implement a 'page' event in a project utilizing DataTables. The provided documentation can be found here -- http://datatables.net/docs/DataTables/1.9.4/#page. Despite t ...

Having trouble with Next-Auth's signIn with Credentials feature in NextJS?

I have recently added the next-auth package to my new Next.js project. Despite following all the documentation for both Next.js and next-auth, I am still unable to resolve the issue. The problem I am encountering is as follows: I am trying to log in to my ...

Storing and Retrieving Multiple Data with localStorage

I need assistance with modifying my code. I have an input field labeled "mail" and I am trying to store email addresses and corresponding IDs in local storage. The email address should be taken from the "mail" input field while the ID should increment each ...

The Three JS on the website is error-free, yet it fails to function properly

I've been attempting to replicate the example three.js page on my own website, complete with a canvas for the 3D animation. However, I'm encountering an issue where nothing is displayed, despite no errors appearing. I've tried troubleshootin ...

Creating a Dropdown Filter using Vanilla JavaScript

I am currently working on a project for one of my college courses, which involves creating a dropdown list filter using pure JavaScript to filter a grid of images in HTML/CSS. The main challenge I am facing is that this filter needs to be able to work with ...

Locate all records in Mongoose that do not have a specific value (using the $ne operator)

In my mongoose query, I am facing an issue where I need to select all rows except for specific ids. Here is a snippet of my code: var ids = [{id: 123},{id: 222},{id:333}]; User.find({_id: {$ne: ids.id }},'firstName lastName _id avatar',functi ...

The backface remains visible despite being designated as "hidden"

I have successfully created a "flip card" in CSS3, where the card flips downward to reveal the other side when a user hovers over it. I have ensured that the back face is not visible by setting backface-visibility to hidden. However, despite my efforts, th ...

The metallic material in Substance Painter appears as a dark shade in A-Frame

After exporting an object as gltf from Substance Painter, I am importing it into my A-frame scene. Strangely, the metallic outer material appears dark in my current scene while other materials like plastic appear white and are visible. Despite already ha ...

The JavaScript for loop using .appendChild() is inserting the values of the final object, represented as [object object], into the HTML document

$(document).ready(function () { GetDetails(); }); function GetDetails() { let albumlist = document.getElementById("album-list"); $.ajax({ url: '/Store/browseajax', type: 'GET', data: { id: '@ ...

Issue with using async await in map function: async function may not complete before moving on to the next item in the

Currently, I have an array that needs to be mapped. Inside the mapping function, there is an asynchronous function being called, which conducts an asynchronous request and returns a promise using request-promise. My intention was for the first item in the ...

I'm looking for guidance on how to properly implement onChange in this particular script. Any help with the correct syntax

Can someone help me with the correct syntax for writing onChange in this script? I want to integrate these phpcode into my script. Here is the Javascript code: ih+='<div class="form-group drop_bottom" id="select_one_'+extra_num+'">< ...

Is it possible to update parent data using a child component?

What is the correct way to update parent data using a child component? In the child component, I am directly modifying parent data through props. I'm unsure if this is the right approach. According to the Vue documentation: When the parent proper ...

Creating a harmonious relationship between a generator using recursion and promises

In Elasticsearch, it's feasible to make a "Scrolling" request. This method involves keeping a cursor open and retrieving large chunks of data gradually. Demo code is available for reference. The provided code uses callbacks and recursion to fetch dat ...

What is the best way to implement a Navbar link in React.js?

I am currently working on developing a website using Reactjs. I have successfully created a Navbar with two links - Home and Contact. However, when I click on the Contact link, although the URL changes accordingly, the page itself does not update. I have s ...

What could be causing the issue with running npx create-react-app my-first-app?

Encountered issues when attempting to execute npx create-react-app. Need assistance troubleshooting the error messages preventing the command from running. View Screenshot of Terminal with stacktrace Error: EPERM: operation not permitted, mkdir 'C:& ...