Nodejs Wait for all promises to resolve and then redirect

207 views Asked by At

I am facing the problem in redirecting to index page. Instead page refreshes to same create page perhaps due to large size images are still copying but why page refreshing instead of images waiting copying to finish and then redirecting.

    module.exports.create_customModel_post = async (req, res) => {
    const {images} = req.files
    
    let myPromise = []

    if (images) {
        const dir = `./public/${req.body.slug}`
        fs.mkdirSync(dir, { recursive: true });
        
        for (let i = 0; i < images.length; i++) {

            const uploadTo = `${dir}/${images[i].name}`            

            myPromise.push(new Promise(function(resolve, reject) {
                
                images[i].mv(uploadTo, (err) => {                    
                    if(err){
                        reject(err);
                    }else{
                        resolve(uploadTo);
                    } 
                });
            }));            
        }
    }    
    
    Promise.all(myPromise).then(function(values) {
        console.log(values),
        // THIS REDIRECT IS NOT WORKING
        res.redirect('/admin/custom-models')
    }).catch(function (reasons) {
        console.log(reasons);
    });    
}

Response from server

POST /admin/create-custom-model - - ms - -
new model is created & saved
[
  './public/testing/attachment_48549925.svg',
  './public/testing/brand-name.png',
  './public/testing/design.svg',
  './public/testing/model-name.png',
  './public/testing/path9080.png',

]
GET /admin/create-custom-model 200 12.375 ms - -

here is form I am using. Removed extra

<main>
    <section class="">
        <div class="container">
            <h1>Create Custom Model</h1>
            <table class="">
                <form enctype="multipart/form-data" method="post">
                                 
                  
                    
                    <tr>
                        <td></td>
                        <td>
                            <input type="file" name="images" multiple>
                            
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <td><a href="/admin/custom-models">Cancel</a> </td>
                        <td><button type="submit" >Save</button></td>
                    </tr>
                </form>
            </table>
        </div>
    </section>
</main>
0

There are 0 answers