Warning: Promise rejection was not handled (rejection id: 3)

As a newcomer to the world of await, I'm struggling to handle errors and rejections properly. The unhandled rejections from the shopify-api.js function keep cropping up, and I can't seem to print all the errors that are coming from my middleware in index.js.

Is there a correct way to handle awaits? How can I ensure that all errors are printed?

index.js

const functions = require('firebase-functions');
const app = require('express')();
const cors = require('cors');

// Handling cross-origin requests
app.use(cors({ origin: true }));

const asyncMiddleware = fn => (req, res, next) => {
    Promise.resolve(fn(req, res, next))
       .catch(err => {
       console.error(err);
       res.json(err)
       })
           .catch(next)
};


app.get('/v1/Test/Shopify', asyncMiddleware( async (req, res, next) => {

req.params.workshopId = "TEST_CR"
req.params.date = "2018-11-30"
req.params.startTime = "11:00"
let result1 = await ShopifyWorkshop.AddDate(req, res, next)
console.log("ShopifyWorkshop.AddDate: Success" .green)

res.status(200).json({message: "Success"})
}));

exports.AddDate = async (req, res, next) => {
  await Helper.CheckParamsIsNull(req.params)

  let wsId = req.params.workshopId
  let wsDate = req.params.date
  let wsTime = req.params.startTime

  // Check if workshop is a level
  if (Helper.IsWorkshopType(wsId)) {
    return await Promise.all(WORKSHOP_TYPE[wsId].levelNames.map( async (typeName) => {
      WORKSHOP_CATEGORY[typeName].codeNames.map( async (codeName) => {
        for (let wsId in WORKSHOP_INFO) {
          if (WORKSHOP_INFO[wsId].codeName === codeName) {
            addVariant(wsId, wsDate, wsTime)
          }
        }
      })
    }))
  } else if (Helper.IsWorkshopCategory(wsId)) {
    return await Promise.all(WORKSHOP_CATEGORY[wsId].codeNames.map ( async (codeName) => {
    for (let wsId in WORKSHOP_INFO) {
      if (WORKSHOP_INFO[wsId].codeName === codeName) {
        await addVariant(wsId, wsDate, wsTime)
      }
    }
  }))
  } else {     
    return await addVariant(wsId, wsDate, wsTime)
  }
}

shopify-api.js

exports.AddAProductVariant = async (id, options) => {
  console.log("Adding variant to product..." + options.option1)

let result = await shopify.productVariant.create(id, options)

console.log("Added product variant: " + options.option1)
return result
}

Answer №1

In the following code snippet:

async (typeName) => {
    WORKSHOP_CATEGORY[typeName].codeNames.map( async (codeName) => {
       …
    })
}

You are generating an array of promises, but failing to utilize them effectively. To ensure all promises are fulfilled before proceeding, wrap the entire operation in another Promise.all statement:

(typeName) => {
    return Promise.all(WORKSHOP_CATEGORY[typeName].codeNames.map( async (codeName) => {
//  ^^^^^^^^^^^^^^^^^^
       …
    }))
}

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

Retrieving data from MySQL using PHP and AJAX with radio button selection

How can I update my code to display data from the database when a radio button is clicked instead of using a drop-down box? Here is an example of my current radio button code: <Input type='Radio' Name='compcase' value='1'/& ...

Variations in output observed from angular function across various sections within DOM

After fetching a list of permissions in the background, my goal is to display a page or an error message based on whether the user has the required permissions. I encountered an unusual issue where both sections of the page are being displayed despite hav ...

Guide to configuring Winston logging with Sequelize correctly

Currently, I am setting up winston with Sequelize and have the code snippet below: const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: path. ...

Submitting a form automatically in React Native using Redux

Is there a way to automatically submit a Redux Form in React Native based on certain conditions being met? I attempted to do so below, but it resulted in a warning. The documentation provides an example for remote submitting, but it uses HTML form's ...

React conditional statement within a map function embedded in a JSX element

Below is the function I have created to generate tabbed items: function ConstructTabs(props) { const tabs = props.tabs; const makeTabs = tabs.map((tab, index) => { <React.Fragment> <input className="input-tabs" id ...

Utilizing an external type definition in JSDoc @typedef

I'm encountering an issue with reducing redundancy when defining my imported types. I am trying to streamline the process, but unfortunately I am running into errors. /** @typedef {import("../types/util")} util @typedef {util.mapBehaviors} m ...

Trouble persisting in loading PopperJS and Bootstrap through RequireJS, despite following the suggested PopperJS version

Struggling to load jquery, popperjs, and bootstrap (v4-beta) using requirejs, I'm consistently encountering this error in the console: Uncaught Error: Bootstrap dropdown require Popper.js (https://popper.js.org) at bootstrap.js:6 at bootstrap ...

Can the V8 JavaScript engine made by Google be used on iOS devices?

Is V8 compatible with iOS? If not, what embeddable JavaScript engine would you suggest? UPDATE: We will only be using it for internal scripting purposes, rather than in combination with HTML rendering. ...

Inject the JavaScript template into an HTML page within a <div> element

Looking for a solution to format JSON API data listing books with title, author, and other properties into HTML? Utilizing ES6 backticks and JavaScript templating, the challenge arises when needing to display two cards per row on the HTML page. The issue l ...

Uncovering the User's Browser Specifically for UC-Mini and Opera-Mini

I'm in need of a script that can identify if the user's browser is uc-mini or opera-mini. These particular browsers do not support the "transition" feature. Therefore, when this specific browser is detected, I would like to deactivate the "trans ...

Modifying npm packages within a web application

I have a web application where I recently installed an npm package. However, I've realized that I need to customize it by adding some code. My attempt to modify the package directly in node_modules hasn't resulted in any visible changes. Is there ...

Loop through the tabs array and display varying views based on conditionals

I am currently working on building tabs and tab panels iteratively to display information, but I am facing issues in getting the desired output. For each name in a list, I need to create a tab and a corresponding tab panel underneath it. For example, the ...

What is the best way to implement CSS properties on Material UI components?

I've recently started exploring Material UI, but I'm having trouble understanding how the spacing properties function. I'm trying to utilize the "spacing" feature for various elements, but it appears that it only works for "Box" components a ...

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

Failure to Trigger Error Callback in Ajax Requests

I am encountering an issue with the error callback not being called when I pass the error function as an object parameter in a function. Strangely, when I define it directly within the ajax code, it works without any problems. var options = new Object(); ...

What steps can be taken to resolve a Mediasoup installation error in a Node.js environment?

While attempting to install the mediasoup library, I ran into an error that has me stumped. If anyone has encountered this issue before or knows how to solve it, any assistance would be greatly appreciated. > <a href="/cdn-cgi/l/email-protection" c ...

Receiving an empty string from Chrome FileReader when dealing with large files (300MB or more)

Objective: The task is to read a file from the user's file system as a base64 string in the browser The size of these files can be up to 1.5GB Challenge: A script that works flawlessly on Firefox, regardless of the file size On Chrome, the script p ...

Discover the route followed by an object containing a specific key within an array of objects

Imagine having an array of dictionaries like the one below. How can I locate the object with id: 121 using JavaScript? I've been struggling to figure this out and would appreciate any hints or algorithms on how to achieve this. The desired result sho ...

Update the div content to completely replace it with fresh data using Ajax

I'm currently working on implementing a currency switcher feature for my website, allowing users to toggle between two different currencies. The site is a reservation platform with a booking form displayed on the left side and the booking details occu ...

Trouble arises with Webpack during the compilation of JavaScript files

I've been tackling a project in Laravel 5.3, smoothly using webpack until I decided to configure ES6 by adding babel packages to my npm module. This caused a code breakdown, prompting me to revert back to the initial setup. However, now every time I m ...