0

我想在 loopback4 控制器方法(TypeScript)中扩展响应。我已经有一个从数据库加载的对象数组,但是这些对象中的每一个都必须通过额外的异步加载数据进行扩展。我如何构建 forEach/map 方法调用?

数组看起来像这样(简化):[{'ID':1},{'ID':2}]

对于这些对象中的每一个我想调用一个方法async getData(record: Record): Promise<Property[]>

据我了解,我需要做这样的事情:

async fetchData()
{
   const records = [{'ID':1},{'ID':2}];
   // code...

   records.forEach((record, index) => {
      records[index].Properties = getData(record);
   });

   // here i need all promises resolved

   return records;
}   

结果是,我有一个带有待处理承诺的数组。我该怎么做才能在返回数组之前解决所有问题?我使用 .map() 和/或 Promise.all() 找到了一些代码片段,但在这些示例中没有找到我的解决方案。也许是因为缺乏知识,但目前我被困住了。

4

2 回答 2

1

你可以试试这个:

async fetchData()
{
   const records = [{'ID':1},{'ID':2}];
   // code...

   const promises = records.map(async (record, index) => {
      records[index].Properties = await getData(record);
   });

   // here i need all promises resolved
   await Promise.all(promises);
   return records;
}   
于 2019-07-23T11:12:59.423 回答
0

您可以使用npm async以下模块执行此操作:-

async fetchData()
{
   const records = [{'ID':1},{'ID':2}];
   // code...

    async.mapLimit(records, 1, function(item, cbk) {
        let Properties = getData(item);

        cbk(null, Properties);
    }, function(err, res) {
        // you will get all promises resolved here
    }); 



   // here i need all promises resolved

   return records;
} 

承诺风格:-

async.mapLimit(files, 10, async file => { // <- no callback!
    const text = await util.promisify(fs.readFile)(dir + file, 'utf8')
    const body = JSON.parse(text) // <- a parse error here will be caught automatically
    if (!(await checkValidity(body))) {
        throw new Error(`${file} has invalid contents`) // <- this error will also be caught
    }
    return body // <- return a value!
}, (err, contents) => {
    if (err) throw err
    console.log(contents)
})
于 2019-07-23T10:44:51.100 回答