Async await function two is failing to execute

I am currently working on a process where I need to unzip a file first, wait for the unzipping process to complete, and then loop through each extracted file to upload it to an S3 bucket. The unzipPromise function is working as expected, successfully unzipping the files in the specified directory. However, the uploadS3Promise function does not seem to be executing at all. Despite no errors being thrown, the function simply runs the unzipping process without proceeding to the uploadS3Promise.

function unzipInput(file, client, project_number, oldpath, newpath) {
    path = `zips/${client}/${project_number}/${file}/`;
    function unzipPromise() {
        return new Promise((resolve, reject) => {
            fse.mkdirsSync(path);
            fs.rename(oldpath, newpath, err => {
                if (err) {
                    throw err;
                }
            });
            fs.createReadStream(newpath).pipe(unzip.Extract({ path }));
        });
    }
    function uploadS3Promise() {
        console.log("running");
        return new Promise((resolve, reject) => {
            // fs.unlinkSync(newpath);
            fs.readdirSync(newpath).forEach(file => {
                uploadToS3(file, client, project_number, path);
                console.log(file, "test");
            });

            if (err) reject(err);
            else resolve("success");
        });
    }
    // New code with async:
    (async () => {
        try {
            await unzipPromise();
            await uploadS3Promise();
        } catch (e) {
            console.error(e);
        }
    })();
}

Answer №1

The uploadS3Promise function is not running because it is still waiting for the unzipPromise to complete. In order for the code to continue executing, you must either resolve or reject a promise.

Therefore, in your code snippet...

function unzipPromise(){
    ...
    resolve(...)
    ...
}

As a side note, it might be more clear to name functions without including "promise" at the end. For example, simply use unzip and uploadS3 as function names. We typically do not name functions based on their return types, such as intIndexOf, etc.

Answer №2

Remember to use the resolve function once the unzip path is completed, or the reject function if an error occurs. Streams act as EventEmitter, allowing you to listen for events and interact with them.

const stream = fs.createReadStream(newpath).pipe(unzip.Extract({ path }))
stream
.on('error', (err) => reject(err))
.on('finish', () => resolve())

Answer №3

In my opinion, utilizing a .then statement can help simplify the process.

unzipPromise().then(res => {
    console.log('resolved promise 1');
    uploadS3Promise();
} rej => {
    console.log('rejected promise 1, sorry!');
});

It's worth noting that the "unzipInput" section is neither resolved nor rejected.

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

Modifying the color of a specific node in jstree

I am attempting to modify the background color of the node I have selected in jstree. $('#syncrep').jstree({ 'core' : { 'data' : repository ...

Include a link to a JavaScript file within a dynamically created HTML page in a Delphi VCL application

I am currently developing a Delphi XE5 VCL Forms Application which includes a TIdHTTPServer on the main form. Within this server, there is a CommandGet procedure called IdHTTPServer: procedure TForm1.IdHTTPServerCommandGet(AContext: TIdContext; ARequest ...

Transform a div's style when hovering over another div using absolute positioning without repetition

I am facing an issue with multiple divs positioned absolutely on top of a primary div with relative positioning. I want one specific div to change its background-color when hovering over another div within the same parent div. Though I know about ad ...

Choosing several checkboxes and populating an array with values - HTML and JavaScript

I am working on a modal dialog that displays a table with checkboxes next to user names. My goal is to link these checkboxes to the respective names so that when a box is checked next to 'Jon' in the table, the name 'Jon' gets selected. ...

How to establish a session in CodeIgniter with the help of JavaScript

Currently, I am trying to save the session in jQuery. Specifically, I am attempting to store all the IDs that are checked via checkboxes in the export_type variable and then save them in the session. However, when running the following code snippet, I en ...

Executing a function with a click, then undoing it with a second click

My goal is to trigger an animation that involves text sliding off the screen only when the burger icon is clicked, rather than loading immediately upon refreshing the page. The desired behavior includes activating the function on the initial click and then ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

Sending data through props to components that can only be accessed through specific routes

File for Router Configuration import DomainAction from './components/domainaction/DomainAction.vue' ... { path: '/domainaction' , component: DomainAction }, ... Linking to Routes using Router Links ... <router-link to="/domainact ...

Creating JavaScript object fields with default values in an AngularJS model: A Step-by-Step Guide

As I work on developing the model layer for my AngularJS application, I came across some valuable advice on using functions to create objects. This source emphasizes the use of functions like: function User(firstName, lastName, role, organisation) { // ...

What is the most effective way to eliminate error messages from the email format checker code?

Recently, I've been working on a code to validate forms using javascript/jquery. One particular issue I encountered was related to checking email format. The problem arose when entering an invalid email - the error message would display correctly. How ...

Display a sublist when a list item is clicked

I am receiving a JSON object in my view that looks like this: $scope.mockData = [ { "folder": "folder1", "reports": [{ "name": "report1" }, { "name": "report2" }, { "name": "report3" }] }, { "folder": "folder2", "reports": [{ "name": ...

The ajax request functions smoothly on the OS X Paw app and cURL, but does not work properly when coded in Javascript / jQuery

Currently delving into the world of ajax requests, I've been utilizing the Paw app to troubleshoot one. Surprisingly, the request functions flawlessly within Paw itself and even the cURL code generated by Paw works like a charm. However, the JavaScrip ...

Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with: import { Document, Schema, Model, model} from "mongoose"; export interface IApplication { id: number; name ...

Creating an AI adversary for a simple Tic Tac Toe game board: a step-by-step guide

Being new to programming, I recently completed a basic Tic Tac Toe gameboard successfully. However, as I progress to the next phase of my assignment which involves implementing an AI opponent, I encountered several challenges. As a novice in programming, ...

Converting an HTML ul-li structure into a JavaScript object: Steps to save the structure

My HTML structure uses ul and li elements as shown below: <ul class="treeview" id="productTree"> <li class="collapsable lastCollapsable"> <div class="hitarea collapsable-hitarea lastCollapsable-hitarea"></div> <span ...

What is the most effective method for incorporating multi-line breadcrumb links in a React application?

I am currently working on implementing a multiline breadcrumb link feature for mobile and tablet devices. As users navigate through multiple folders, I need to handle scenarios where the number of links exceeds the maximum allowed in the breadcrumb contain ...

Issues with the ES version affecting back4app cloud code functions

Utilizing back4app as my backend service for deploying my React Native and JS app, I am currently experimenting with the 'Cloud Code Functions' feature. Being new to back4app, I encountered an issue when following their guide. I received this er ...

Troubleshooting Knockout.JS: Why self.myObservable is not working and the importance of code organization

My webpage uses knockout to handle a search field, dropdown selection, and page number. These elements are all initialized with default values for the first run or when the page is accessed. I'm encountering an error that says: "self.selectedTeamId i ...

It appears that the functionality of RegExp.prototype.exec() is not functioning as expected

const fs = require('fs') const jsdocFinder = /\/\*\*\n(.+?)\*\//gs /** * Implementing a function to convert JSDocs into JSON format. * @function * @param {String[] | String} dirs The directory or directories of ...

The Facebook messenger checkbox plugin does not appear to be displaying correctly

I have integrated the Facebook Messenger Checkbox Plugin into my AngularJS application by following the guide provided at this link. Initially, I was able to successfully display the messenger checkbox plugin on a page. However, upon navigating to another ...