【问题标题】:function not returning value from amazon-s3 file but prints when i console [duplicate]函数未从 amazon-s3 文件返回值,但在我控制台时打印 [重复]
【发布时间】:2019-12-25 19:07:11
【问题描述】:

以下代码不返回 amazon s3 内容,它在控制台数据值时起作用。 我尝试在函数外声明变量并尝试从函数返回,但不起作用

const getMeridianToken1 = () =>{

  s3 = new aws.S3();

  // Create the parameters for calling listObjects
  var bucketParams = {
    Bucket: 'bucket-name',
    Key: 'access_token.json'
  };

  // Call S3 to obtain a list of the objects in the bucket
  s3.getObject(bucketParams, function(err, data) {
    if (!err) {
      var result = JSON.parse(data.Body.toString());
      console.log("working here---",result.access_token);
      return result.access_token; //this is not returning
    }
  });
  //return JSON.parse(data.Body.toString()); //if hard code here it works, if i return s3 conteent the data variable not available here
}

console.log("not working",getMeridianToken1);

【问题讨论】:

    标签: javascript node.js amazon-s3 graphql


    【解决方案1】:

    问题是 s3 方法是异步的。看到这个

    function getMeridianToken1() {
      const s3 = new aws.S3();
    
      // Create the parameters for calling listObjects
      var bucketParams = {
        Bucket: 'bucket-name',
        Key: 'access_token.json'
      };
      return new Promise((resolve, reject) => {
        s3.getObject(bucketParams, function(err, data) {
          if (!err) {
            var result = JSON.parse(data.Body.toString());
            resolve(result.access_token);
          }
          reject(err);
        });
      });
    }
    
    getMeridianToken1()
      .then(val => console.log(val));
    
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      s3.getObject 是控件在返回 JSON.parse() 行早期到达的异步调用,这就是数据变量在回调函数之外不可用的原因。

      解决方案是将 s3.getObject 包装在 promise 中或使用 async/await。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-02
        • 2017-01-30
        • 1970-01-01
        • 2018-09-15
        • 2021-02-09
        • 1970-01-01
        • 2020-01-26
        • 2017-08-13
        相关资源
        最近更新 更多