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?

Upvotes: 3

Views: 499

Answers (1)

Prakash Bhosale
Prakash Bhosale

Reputation: 247

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
    }

});

Upvotes: 1

Related Questions