英文:
How to use it with promise string label in javascript
问题
我正在尝试使用如下的 Promise。
```typescript
let promiseArray: [string, Promise<unknown>][] = [];
for(const a of array)
{
const promise = new Promise(() => {this.repository.getRepository<a.entity>.find()});
promiseArray.push([a.entityName, promise]);
}
上述代码的结果是:
result : [
['EntityName', [{},{},{}]],
['EntityName2', [{},{},{}]],
....
]
但我不知道如何将 promiseArray 应用到 Promise.all
。
await Promise.all(promiseArray)
.then((res) => {
console.log(res);
})
.catch((e) => console.error(e));
我尝试了上述方法,但没有起作用,也尝试了 promiseArray.map((pm)=>pm[1])
,但我无法映射出 pm[0]
的值。
英文:
I am trying to use a promise as below.
let promiseArray: [string, Promise<unknown>][] = [];
for(const a of array)
{
const promise = new Promise(() => {this.repository.getRepository<a.entity>.find()});
promiseArray.push([a.entityName, promise]);
}
And the result of the code above is:
result : [
['EntityName', [{},{},{}]],
['EntityName2', [{},{},{}]],
....
]
But I don't know how can I apply promiseArray to promise.all
.
await Promise.all(promiseArray)
.then((res) => {
console.log(res);
})
.catch((e) => console.error(e));
I tried the above, but it didn't work, and I tried promiseArray.map((pm)=>pm[1])
, but I couldn't map the value of pm[0]
.
答案1
得分: 1
看起来你在填充数组时出了一些问题。根据你的代码,似乎你在使用TypeORM,并且.find()
是异步的(返回一个Promise)。所以,你不需要再包装它成另一个Promise。尝试这样填充数组:
let promiseArray: [string, Promise<unknown>][] = [];
for(const a of array)
{
const promise = this.repository.getRepository<a.entity>.find();
promiseArray.push([a.entityName, promise]);
}
然后,你只需要使用.map()
来获取数组中的第二个值,即.find()
返回的Promise:
await Promise.all(promiseArray.map(el => el[1]));
如果你需要将.entityName
与Promise的结果一起传递,那么可以将每个元素映射到它的.find()
Promise,然后在.then()
中将实体名称添加到结果中。这样为array
中的每个元素创建了一个单独的Promise,可以简单地传递给Promise.all()
:
const promiseArray: [Promise<[string, unknown]>][] = array.map(el => this.repository.getRepository<a.entity>.find().then(res => [el.entityName, res]));
const results = await Promise.all(promiseArray);
英文:
It looks like you're populating your array wrong. From your code, it looks like you're using TypeORM, and that .find()
is async (returns a promise). So, you don't need to wrap it in another promise. Try filling the array like this:
let promiseArray: [string, Promise<unknown>][] = [];
for(const a of array)
{
const promise = this.repository.getRepository<a.entity>.find();
promiseArray.push([a.entityName, promise]);
}
Then, all you need to do is a .map()
to get the second value in the array, which is the promise returned by .find()
:
await Promise.all(promiseArray.map(el => el[1]));
If you need to pass the .entityName
along with the promise's result, then map each element to its .find()
promise, then add the entity name to the result in a .then()
. This creates a single promise per element in array
and can be simply passed to Promise.all()
:
const promiseArray: [Promise<[string, unknown]>][] = array.map(el => this.repository.getRepository<a.entity>.find().then(res => [el.entityName, res]));
const results = await Promise.all(promiseArray);
答案2
得分: 1
Promise.all
接受一个 Promise 数组,但你有一个数组类型为 -
Array<[String, Promise]>
你需要以不同方式构建 Promise 数组 -
const promiseArray: Promise<Array<[string, unknown]>> = []
for (const a of array) {
const promise = new Promise((resolve, reject) => {
// ...
})
.then(result => [a.entityName, result]) // ✅
promiseArray.push(promise)
}
现在你可以使用 Promise.all
-
Promise.all(promisesArray).then(...)
结果为 -
[
['EntityName', <promise result>],
['EntityName2', <promise result>],
...
]
这里有一个可运行的示例 -
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const randPromise = () =>
new Promise(r =>
setTimeout(r, 1000, Math.random() * 100 | 0)
)
const labels = ["a", "b", "c", "d"]
const promises = []
for (const label of labels)
promises.push(randPromise().then(value =>
[label, value]
))
Promise.all(promises)
.then(JSON.stringify)
.then(console.log)
.catch(console.error)
// [["a",53],["b",25],["c",22],["d",53]]
<!-- end snippet -->
不使用 for..of
循环,许多人发现使用数组的 map
函数更容易 -
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const randPromise = () =>
new Promise(r =>
setTimeout(r, 1000, Math.random() * 100 | 0)
)
const labels = ["a", "b", "c", "d"]
Promise all(labels.map(label =>
randPromise().then(value => [label, value])
))
.then(JSON.stringify)
.then(console.log)
.catch(console.error)
// [["a",90],["b",20],["c",76],["d",60]]
<!-- end snippet -->
每个 then
表达式都有一个等效的 async..await
表示。这种方法使用更少的嵌套 lambda,因此更容易理解 -
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const randPromise = () =>
new Promise(r =>
setTimeout(r, 1000, Math.random() * 100 | 0)
)
const labels = ["a", "b", "c", "d"]
Promise all(labels.map(async label =>
[label, await randPromise()]
))
.then(JSON.stringify)
.then(console.log)
.catch(console.error)
// [["a",90],["b",20],["c",76],["d",60]]
<!-- end snippet -->
英文:
Promise.all
accepts an array of promises, but you have an array of -
Array<[String, Promise]>
You will need to construct the array of promises differently -
const promiseArray: Promise<Array<[string, unknown]>> = []
for (const a of array) {
const promise = new Promise((resolve, reject) => {
// ...
})
.then(result => [a.entityName, result]) // ✅
promiseArray.push(promise)
}
Now you can use Promise.all
-
Promise.all(promisesArray).then(...)
Results in -
[
['EntityName', <promise result>],
['EntityName2', <promise result>],
...
]
Here's a functioning example -
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const randPromise = () =>
new Promise(r =>
setTimeout(r, 1000, Math.random() * 100 | 0)
)
const labels = ["a", "b", "c", "d"]
const promises = []
for (const label of labels)
promises.push(randPromise().then(value =>
[label, value]
))
Promise.all(promises)
.then(JSON.stringify)
.then(console.log)
.catch(console.error)
// [["a",53],["b",25],["c",22],["d",53]]
<!-- end snippet -->
Instead of using the for..of
loop, many find it easier to use an array's map
function -
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const randPromise = () =>
new Promise(r =>
setTimeout(r, 1000, Math.random() * 100 | 0)
)
const labels = ["a", "b", "c", "d"]
Promise.all(labels.map(label =>
randPromise().then(value => [label, value])
))
.then(JSON.stringify)
.then(console.log)
.catch(console.error)
// [["a",90],["b",20],["c",76],["d",60]]
<!-- end snippet -->
Every then
expression has an equivalent async..await
representation. This approach uses fewer nested lambdas and therefore a bit easier to digest -
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const randPromise = () =>
new Promise(r =>
setTimeout(r, 1000, Math.random() * 100 | 0)
)
const labels = ["a", "b", "c", "d"]
Promise.all(labels.map(async label =>
[label, await randPromise()]
))
.then(JSON.stringify)
.then(console.log)
.catch(console.error)
// [["a",90],["b",20],["c",76],["d",60]]
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论