简体   繁体   中英

how to return a function inside a function javascript/nodejs?

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);

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);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM