0

i am trying to return the url i get inside the getsignedurl. when i try this url1 is undefined

function getPublicUrl(filename) {
          var url1;
          var file = bucket.file(filename);

          file.getSignedUrl({
              action: 'read',
              expires: '03-17-2025'

          }, function (err, url) {
              if (err) {
                  console.error(err);
                  return;
              } else {
              url1  = url
                  console.log(url);

              }

          });
       return url1;
 }

then in another function i would call the getpublicurl

stream.on('finish', function() {
          req.file.cloudStorageObject = gcsname;
          req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
1
  • It looks like file.getSignedUrl is asynchronous, so return url1; is run before url1 is set in the callback function. Commented Mar 20, 2016 at 2:03

1 Answer 1

1

file.getSignedUrl seems to be an asynchronous function, you can use ES6 Promise in getPublicUrl, some way like this

function getPublicUrl(filename) {
  return new Promise(function(resolve, reject) {
    var file = bucket.file(filename);
    file.getSignedUrl({
      action: 'read',
      expires: '03-17-2025'
    }, function(err, url) {
      if (err) {
        reject(err);
      } else {
        resolve(url);
      }

    });
  });
}

stream.on('finish', function() {
  getPublicUrl(gcsname).then(function(url) {
    console.log(url);
    req.file.cloudStorageObject = gcsname;
    req.file.cloudStoragePublicUrl = url;
  }).catch(function(err) {
    console.log(err);
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.