与匿名函数交互时,Aync /等待获取值太晚。 AWS

时间:2019-02-28 12:01:45

标签: javascript amazon-web-services asynchronous amazon-s3 async-await

我正在尝试从在线服务中获取数据,但是当我评估它时,它是不确定的。更精确地:

 async function GetDataAndPaths(name) {

  const Paths= await getPaths("Unrelated String", name);
  //those Paths arrive perfectly 

  //we try to get data from those Paths, and we have to do it for every Path
  for (const path of Paths) {
    const data = await getDataFromPath(path.Source.S)
    console.log(data)
  //this log always has undefined value, despite we are using await :/

  }
async function getDataFromPath(Source) {

  const params=...; //params needed for the request

  //this call to an online service (amazon web services) is asynchronous 
  s3.getSignedUrl('getObject', params, function(err, data) {

console.log(data) 
//this log comes so later than the first one and is not undefined, it has the value needed. 
  return data
        })

}

我尝试执行回调和其他操作,但是我对此一无所知。我无法更改从S3方法获取数据的方式,它必须是匿名函数,并且我不能逃避获取所有数据的时间太晚。我想我可以创建一个全局变量(window.PathData之类)并在s3调用中分配它,然后在GetPaths函数中等待该全局变量被填满,但这似乎不是正确的方法

**编辑

我终于成功了:

 const getSignedUrlPromise = (operation, params) =>
   new Promise((resolve, reject) => {
     var s3 = new AWS.S3();
     s3.getSignedUrl(operation, params, (err, url) => {
       err ? reject(err) : resolve(url);
     });
   });

 const p =  await getSignedUrlPromise('getObject', params).catch((err) => console.error(err));

谢谢!

0 个答案:

没有答案