How to wait until update_stream() finishes?

Options
Empty
Empty Member Posts: 1
edited November 2023 in Developer APIs

Hello guys,

i am facing the problem, that my backend server is executing the return-Statement before actually finishing the upload_stream()-method.

The code:

app.post('/changeAvatar', upload.single('file'), async (req, res) => {

  let url = "";

  let cld_upload_stream = cloudinary.uploader.upload_stream(

    {

      folder: "avatar"

    },

    async function(error, result) {

        const query = { username: req.body.username };

        url = result.url;

        await User.findOneAndUpdate(query, { pathToAvatar: result.url });

    }

    );

  streamifier.createReadStream(req.file.buffer).pipe(cld_upload_stream);

  return res.status(200).json({ pathToAvatar: url})

  });


Basically, my backend is sending the JSON to the Frontend, before streamifier.createReadStream(req.file.buffer).pipe(cld_upload_stream); is actually finished? Can someone help me, how to solve this problem?

Answers

  • Wissam
    Wissam Member, Cloudinary Staff Posts: 69
    Options

    Hi there,

    To wait until the upload_stream() method finishes, you can use the Promise object to wait for the result. Here’s an example of how you can modify your code to wait for the upload to complete:

    app.post('/changeAvatar', upload.single('file'), async (req, res) => {
    
      let url = "";
    
      let cld_upload_stream = cloudinary.uploader.upload_stream(
    
        {
    
          folder: "avatar"
    
        },
    
        async function(error, result) {
    
            const query = { username: req.body.username };
    
            url = result.url;
    
            await User.findOneAndUpdate(query, { pathToAvatar: result.url });
    
            res.status(200).json({ pathToAvatar: url});
    
        }
    
        );
    
      streamifier.createReadStream(req.file.buffer).pipe(cld_upload_stream);
    
      await new Promise((resolve, reject) => {
        cld_upload_stream.on('finish', resolve);
        cld_upload_stream.on('error', reject);
      });
    
    });
    

    In this modified code, we use an Promise object to wait for the upload_stream() method to finish. We are adding an event listener to the cld_upload_stream object that will resolve the Promise when the upload is complete. We are also adding an error listener to reject the Promise if there is an error during the upload.

    I hope this helps!

    Regards,

    Wissam