JavaScript promises: Unable to update objects and arrays inside .then()

114
March 10, 2018, at 11:46 PM

This is my very first thread in StackOverflow so I will do my best to do it understandable and clear:

So: in my NodeJS application I have this function to register a user in the database. This one is a simplified version, but it consists of 3 promises that do all the necessary checks and generate the necessary data.

If one of this promises fail, I want to add the error information inside an object that at the very last stage will be returned with the result of the operation. However, in some cases, the "result" object and its "errors" array inside are not updating.

Why is this happening?

function createNewUser(userData) {
// Initialize the object for storing the result:
let result = {
    result: 'fail',
    errors: [],
};

// Promise 1: [STACKOVERFLOW: EVERYTHING OK HERE]
// Create a random User ID:
let promise1 = new Promise(function (resolve, reject) {
    userData.UserID = makeUserID(12);
    resolve();
});

// Promise 2: [STACKOVERFLOW: HERE DATA IS PUSHED CORRECTLY TO THE "result.errors" ARRAY :) ]
// Detect and clean input fields:
let promise2 = new Promise(function (resolve, reject) {
    if (!detectOrValidateUserIdentifier(userData.username) !== 'username') result.errors.push('invalid_username');
    if (!detectOrValidateUserIdentifier(userData.email) !== 'email')       result.errors.push('invalid_email');
    if (!detectOrValidateUserIdentifier(userData.phone) !== 'phone')       result.errors.push('invalid_phone');
    if (!validatePasswordFormat(userData.password))                        result.errors.push('invalid_password_format');
    // Do an error check-up:
    if (result.errors.length >= 1) {
        reject();
    }
    resolve();
});

// Promise 3: [STACKOVERFLOW: HERE WE HAVE PROBLEMS]
// Check for coincidences using the same data in the database:
let promise3 = new Promise(function (resolve, reject) {
    // Find out if the user name, email or phone are in use::
    SQLretrieveUser(data = {
        UserName: userData.username,
        EmailAddress: userData.email,
        PhoneNumber: userData.phone
    })
        .then(function (returnedValue) {
            if (returnedValue.length > 0) {
                // In case of finding one or more than one matching accounts reject the promise.
                result.errors.push('not_unique_data'); // [STACKOVERFLOW: Not working, not being returned with the main function.]
                reject(); // I think this is causing UnhandledPromiseRejectionWarning. It is being already rejected at some point (???)
            } else {
                resolve();
            }
        })
        .catch(function (returnedValue) {
            // In case of error in the database query:
            result.errors.push('internal_error');
            reject();
        });
});

// Final stage: [STACKOVERFLOW: HERE I AM HAVING THE SAME ISSUE]
Promise.all([promise1, promise2, promise3])
    .then(function() {
        // When all the promises were successful pass it onto the function that saves the data (this is a promise)
        databaseOperations.saveUser(userData)
            .then(function() { // The script finished successfully here.
                // [STACKOVERFLOW: Same issue here]
                result.result = 'OK'; // Not working.
            })
            .catch(function(returnedValue) { // For errors storing the data in the database.
                result.errors.push('internal_error') // Is this even working?
            });
    });
return result;

}

READ ALSO
Multer - Cannot Read Property “path” of Undefined

Multer - Cannot Read Property “path” of Undefined

I'm trying to upload a single image to mongo using multer but I keep getting this error while trying to access the image path like:

159
How to get attributes from through table in query?

How to get attributes from through table in query?

I'm making a simple shopping cartI have a Cart model, a Product model and a through table CartItems

131
how to merge object of multiple json into one json file using node.js

how to merge object of multiple json into one json file using node.js

I have multiple json files which just want to merge particular object from them and then save it into new json file: for example:

189
TypeError: Cannot read property 'userAgent' of undefined error on node.js app run

TypeError: Cannot read property 'userAgent' of undefined error on node.js app run

Hello I'm trying to get pdfreader module to work in nodejs to convert PDFs into text format

127