简体   繁体   English

如何从Node.js中的两个嵌套回调函数返回数据

[英]How to return data from two nested callback function in nodejs

I need to return the s3Url array. 我需要返回s3Url数组。 How to return s3Url array and suggest me is there any other best way to upload the data to s3 and return the s3Url 如何返回s3Url数组并建议我还有其他最佳方法将数据上传到s3并返回s3Url

exports.s3Media = fileName => {
          let s3Url = [];
          (async () => {
            for (let i = 0; i < 6; i++) {
              await fs.readFile(`${fileName[i]}`, (err, data) => {
                if (err) throw err;
                const params = {
                  Bucket: `research-1`,
                  Key: fileName[i],
                  Body: JSON.stringify(data, null, 2)
                };
                s3.upload(params, function(s3Err, data) {
                  if (s3Err) throw s3Err;
                  s3Url.push(data.location);
                });
              });
            }
            return s3Url;
          })();
        };

There are more things wrong with your code. 您的代码还有更多问题。 You are not using Async/Await in the right way. 您没有以正确的方式使用Async / Await。

  1. Take a look at Async/Await: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function 看看Async / Await: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function

  2. If you want to go with the Async/Await you have to promisify readFile(), have a look at this answer here: reading file with ES6 promises 如果要使用Async / Await,则必须保证readFile()正确,请在此处查看以下答案: 使用ES6 Promise 读取文件

  3. Why are you using a self invoking fn inside the s3Media, maybe you can make the whole fn async (this will return a promise) 为什么在s3Media中使用自调用fn,也许可以使整个fn异步(这将返回一个Promise)

  4. The return is not in the right position 退货位置不正确

Dig a little on your own and you will get there. 自己挖一点,您将到达那里。 I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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