How to Wait for ServerAction to complete before moving to next?

For the longest Time i’ve had “Waits” of just a second value to ensure proper running…

How do you wait until the last function is complete before moving to the next task?

This would also drastically speed up my code!

Server action steps are executed synchronous, which means each step runs only after the previous one has completed. The wait steps here not needed, they only slow down your server action.

API Loads Image >> Sharp Resize (Custom Module) >> Load image attempts to run before “Sharp Resize” is complete…

How do I fix this issue?

You’ll need to post the code for your custom module, as that is where the issue lies.

Ok see below. I’ve been creating custom modules and they work but I dont think I understand how to create a proper “Response / Return” value and catch for error.

If anyone can help i’d be forever greatful! See code below.

const fs = require("fs");
const fetch = require('node-fetch');
const sharp = require("sharp");
const { toSystemPath } = require('../../../lib/core/path');

exports.getValue = function (options) {
    let path_input = toSystemPath(this.parseRequired(this.parse(options.path_input), 'string', 'fs.exists: path is required.'))
    let path_output = toSystemPath(this.parseRequired(this.parse(options.path_output), 'string', 'fs.exists: path is required.'))

    let width = this.parse(options.width)
    let height = this.parse(options.height)
    let fit = this.parse(options.fit)
    let file_name = this.parse(options.file_name)
    // const destinationImagePath = `uploads/temp_usr_upload/${srcImgName}.png`;    //where new image will be saved

    console.log("Before Resize")

    const resizeImage = async () => {
        console.log("Started Resize")
        const image = await sharp(path_input)
            .trim()
            .resize(1000, 1000, {
                fit: 'contain',
                background: { r: 255, g: 255, b: 255, alpha: 0.0 }
            }
            )        
            .median(3)
            .sharpen(100)
            .ensureAlpha(0)
            .toFile(path_output + "/resized-" + file_name);
        return image;
    };
    resizeImage();

};

I’m by no means an expert here, but try these changes:

exports.getValue = function (options) {

becomes

exports.getValue = async function (options) {

and

resizeImage();

becomes

await resizeImage();

If that doesn’t work, I’m sure somebody with more node.js experience will easily solve this. Your function is just not waiting for the process to complete before returning.

1 Like

Thanks Ken,

That didn’t seem to fix it.

The function itself works properly regardless of how I put it, I just need to figure out how to return a response I believe so that it does not “jump” to the next server action.

In addition to what Ken wrote, try:

return await resizeImage();
1 Like

This did it!

Solved. Thanks!