How to deal with sync and Async function results?

38 Views Asked by At

Hello guys i have a function that i need to calc the total duration of media preview. Media array has videos and images. If media is image, just add 5 seconds. If media is video, find it's duration and add to the total.

Next function should return the totalPreview time. The problem is how to deal with this. If i use .then() to promise , the promise will execute after the main function and the return result will not contain this promise's data.

 getItemsDuration(mediaArray: any) {
    let previewTime: number = 0;
    for (let media of mediaArray) {
        let isVideo = !!(
            (media.locationFile as any)?.type as string
        )?.includes('video');

        if (isVideo) {
            //Async Returns the promise, I need to add the result to previewTime
            let promise = this.getVideoDurationPromise(media.locationFile);
    
        } else {
            // If it isn't video just add 5 sec duration
            previewTime += 5;
        }
    }

    return   previewTime;
}

Here is the promise. I have the Url of the video and i use 'loadedmetadata' event to get it's duration. Then i return the promise

    private getVideoDurationPromise(file: File): Promise<number> {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            const media = new Video(reader.result as string);
            media.onloadedmetadata = () => resolve(media.duration);
        };
        reader.readAsDataURL(file);
        reader.onerror = (error) => reject(error);
    });
}

I think that a solution is to transform not video file results to promises and return a promises Array, but it will be a problem to the function that this promises array will end up.

Can someone help me how to deal with that?

0

There are 0 best solutions below