gpt4 book ai didi

javascript - 与 lodash 的 promise

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:52 25 4
gpt4 key购买 nike

我正在尝试使用 _.times 生成用户列表,但我得到了一组 Promised 对象。如何输出普通对象数组?

const createUser = async () => ({

});

const users = [];

_.times(5, () => users.push(createUser()));

Promise.all(users);

输出

[ Promise { { username: 'Armando', password: '8cw0W7Jpm0LSSS9' } },
Promise { { username: 'Lauren', password: '9oFCK4rqLj_DGol' } },
Promise { { username: 'Frederique', password: 'JXGOsjCCOMFBYFd' } },
Promise { { username: 'Otilia', password: 'DnxArNIsjaVoMB2' } },
Promise { { username: 'Elisabeth', password: 'kZbSlg7bVWiagFT' } } ]

预期

[
{ username: 'Armando', password: '8cw0W7Jpm0LSSS9' },
{ username: 'Lauren', password: '9oFCK4rqLj_DGol' },
{ username: 'Frederique', password: 'JXGOsjCCOMFBYFd' },
{ username: 'Otilia', password: 'DnxArNIsjaVoMB2' },
{ username: 'Elisabeth', password: 'kZbSlg7bVWiagFT' }
]

最佳答案

只需等待 Promise.all 的结果:

const users = await Promise.all(userPromises)

编辑

使用 await 当然只能在 async 函数内工作——感谢 Olian02 在评论中指出这一点。

关于javascript - 与 lodash 的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51232081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com