我有一组包含视频元数据的对象。我需要遍历它,对于每个对象,我需要通过它的 filename
进行 API 调用以获取 streamingLink
并将其分配给对象的 streamingLink
。我的问题是当我返回这个数组时,该数组是未定义的。我如何告诉代码等待直到分配了流链接?
这是我的代码的样子:
// get array from database
const items = await client.db('database').collection('collection').find({}).toArray();
// for each object get and replace streamingLink
let items_withLinks = items.map((item) => {
getStreamingLink(item.filename) // API call to get link
.then(response => {
item.streamingLink = response.result.link;
return item;
})
});
console.log(items_withLinks); // undefined
我尝试在不同的地方使用 await
并将其包装在 async
函数中,但我想不出正确的方法。
答案 0 :(得分:2)
您可以遍历数组并为每个项目创建一个承诺。然后你可以调用Promise.all。
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// expected output: Array [3, 42, "foo"]
答案 1 :(得分:1)
根本问题是您在 .map
中使用的函数不返回任何内容。 (因此,从技术上讲,您实际上将获得一组 undefined
值,而不是 undefined
本身 - 但这显然不好。)
您需要 return
承诺,然后使用 Promise.all
获取结果数组。
// get array from database
const items = await client.db('database').collection('collection').find({}).toArray();
// for each object get and replace streamingLink
let items_withLinks = items.map((item) => {
// return is the only thing I've added here!
return getStreamingLink(item.filename) // API call to get link
.then(response => {
item.streamingLink = response.result.link;
return item;
})
});
const result = await Promise.all(items_withLinks);
console.log(result);