Editor uploading files to S3 wait for completition.

Editor uploading files to S3 wait for completition.

naspersgaspnaspersgasp Posts: 53Questions: 14Answers: 1
edited August 2018 in General

Hi,

Good day.

Found some resources that pointed me in the right direction to get an upload to S3 working with the NodeJS server package.

My question is around how to wait for the upload to complete before returning the file id. My code is:

.fields(
  new Field('id').upload(
    new Upload(function(fileInfo, id) {
      let params = {...}
      s3.putObject(params, function(err, data) {
        if (err) {
          console.debug('There was an error creating file: ' + err.message);
        }
        else {
          console.debug(`Successfully created. Id ${id} file ${fileInfo.filename}.`);
        }
      });

      return id;
  })

For some reason I can't get the function to wait until the upload has finished before returning the id. Which means I can't display the file as it has not uploaded completely yet.

I've tried the following, thinking that the await/async might work:

.fields(
  new Field('id').upload(
    new Upload(async function(fileInfo, id) {
      let params = {...}
      await s3.putObject(params, function(err, data) {
        if (err) {
          console.debug('There was an error creating file: ' + err.message);
        }
        else {
          console.debug(`Successfully created. Id ${id} file ${fileInfo.filename}.`);
        }
      });

      return id;
  })

Regards.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin
    Answer ✓

    The Upload class does accept an async function as the callback. I think the issue here is that the s3.putObject function isn't returning a promise, so you'd need to do something like:

    .fields(
      new Field('id').upload(
        new Upload(function(fileInfo, id) {
          let params = {...}
          return new Promise( function (resolve, reject) {
            s3.putObject(params, function(err, data) {
              if (err) {
                console.debug('There was an error creating file: ' + err.message);
                reject( 'Error' );
              }
              else {
                console.debug(`Successfully created. Id ${id} file ${fileInfo.filename}.`);
                resolve( id );
              }
            });
      })
    

    I'll confess I haven't tested it, so I might have made some daft syntax error, but that is how you can use a callback based async function with async/await.

    The other option is to use util.promisify which I really like :).

    Allan

  • naspersgaspnaspersgasp Posts: 53Questions: 14Answers: 1

    Hi,

    Thanks. Once again you are lengen! :) Syntax is spot on!

    Regards.

This discussion has been closed.