Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

469
Views
nodejs async await flow not working correctly

I want to create an endpoint for downloading a video and upload this video to Youtube.

So firstly I getting video url from request body. Secondly I saving this video to temp folder. After that I upload this video to YouTube channel and Last step is deleting temp video.

So my code snipped like that:

    const videoUrl = req.body.video_url;
    ....
    ....
    var download = async function (url: any, dest: any, cb: any) {
        var file = fs.createWriteStream(dest);
        var request = https.get(url, function (response: any) {
            response.pipe(file);
            file.on('finish', function () {
                file.close(cb);
            });
        }).on('error', function (err: any) {
            fs.unlink(dest);
            if (cb) cb(err.message);
        });
    };

    const video = await download(videoUrl, file, function () {
        console.log('Video Download Successfull');  ===============> 3rd console output
    });
    ....
    ....
    var readStream = await fs.createReadStream(file);
    readStream.on('error', function (err: any) {

    });

    var request: any = await Youtube.videos.insert({
        resource: {
            snippet: {
                title: title
                , description: description
            }
            , status: {
                privacyStatus: "private"
            }
        }
        , part: "snippet,status"
        , media: {
            body: readStream
        }
    }, (err: any, data: any) => {
        if (err) {
            console.log(err.response.data.error)
            res.status(500).json({
                status: "Fail",
                message: "Youtube Video Upload Failed"
            })
        }
        else {
            try {
                fs.unlinkSync(file)
                console.log("temp video file deleted from server"); ===============> 1st console output
            } catch (err) {
                console.log("temp video file not deleted")
                console.error(err)
            }
            res.status(200).json({
                status: "Success",
                message: "Youtube Video Upload Successfull"
            })
            console.log("Video upload to youtube Successfull."); ===============> 2nd console output
        }

    });

When I call this endpoint, console output like that:

temp video file deleted from server  
Video upload to youtube Successfull. 
Video Download Successfull

But console output should be :

Video Download Successfull
Video upload to youtube Successfull.     
temp video file deleted from server  

Why my flow is incorrect. How can I solve this?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

you will have to use Promises, here i used promises to download video function.

const videoUrl = req.body.video_url;
....
....
var download = async function (url: any, dest: any, cb: any) {
    return new Promise((resolve, reject) => {
        try {
            var file = fs.createWriteStream(dest);
            var request = https.get(url, function (response: any) {
                response.pipe(file);
                file.on('finish', function () {
                    file.close(cb);
                    resolve(true)
                });
            }).on('error', function (err: any) {
                fs.unlink(dest);
                if (cb) cb(err.message);
                reject(false)
            });
        }catch (e) {
            reject(false)
        }
        })
};

const video = await download(videoUrl, file)
if (video){
    console.log('download success')
}
....
....
var readStream = await fs.createReadStream(file);
readStream.on('error', function (err: any) {

});

var request: any = await Youtube.videos.insert({
    resource: {
        snippet: {
            title: title
            , description: description
        }
        , status: {
            privacyStatus: "private"
        }
    }
    , part: "snippet,status"
    , media: {
        body: readStream
    }
}, (err: any, data: any) => {
    if (err) {
        console.log(err.response.data.error)
        res.status(500).json({
            status: "Fail",
            message: "Youtube Video Upload Failed"
        })
    }
    else {
        try {
            fs.unlinkSync(file)
            console.log("temp video file deleted from server"); ===============> 1st console output
        } catch (err) {
            console.log("temp video file not deleted")
            console.error(err)
        }
        res.status(200).json({
            status: "Success",
            message: "Youtube Video Upload Successfull"
        })
        console.log("Video upload to youtube Successfull."); ===============> 2nd console output
    }

});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!