简体   繁体   English

Promise.all 返回另一个 promise

[英]Promise.all returns another promise

I have the following functions in Javascript:我在 Javascript 中有以下功能:

// fetches the username based on the user ID

const fetchUsername = async (userId) => {
    const response = await axios({ ... });
    return {
        userId,
        username: response.data.username
    }
};

// fetches the online status based on the user ID

const fetchOnline = async (userId) => {
    const response = await axios({ ... });
    return {
        userId,
        online: response.data.online
    }
};

const fetchUsers = (userIds) => {
    const promises = [];
    userIds.forEach(userID => {
        return new Promise(async (resolve, reject) => {
            const usernameObject = await fetchUsername(userId);
            const onlineObject = await fetchOnline(userId);
            resolve({ ...usernameObject, ...onlineObject });
        })
    })
    Promise.all([promises]).then(response => console.log(response));
};

I have 2 questions about this piece of code:我对这段代码有两个问题:

  1. the response in Promise.all().then() is another promise. Promise.all().then() 中的响应是另一个 promise。 It's not an array with objects containing usernames and online statuses, but promises (like this: {"_40": 0, "_55": null, "_65": 0, "_72": null} ).它不是包含用户名和在线状态的对象的数组,而是承诺(像这样: {"_40": 0, "_55": null, "_65": 0, "_72": null} )。

  2. using async/await in new Promise is anti-pattern, but I have no idea how I can combine the results of the 2 promises to 1 object.在新的 Promise 中使用 async/await 是反模式,但我不知道如何将 2 个 promise 的结果结合到 1 个 object。

EDIT:编辑:

I can only accept one answer, but the answer from Gabriel Donadel Dall'Agnol helped me with question 1 and the answer from Klaycon helped me with question 2.我只能接受一个答案,但 Gabriel Donadel Dall'Agnol 的回答帮助我解决了问题 1,而 Klaycon 的回答帮助我解决了问题 2。

Thank you very much everybody!非常感谢大家!

You just missed populating the promises array您只是错过了填充promises数组

const fetchUsers = (userIds) => {
const promises = userIds.map(userID => {
    return new Promise(async (resolve, reject) => {
        const usernameObject = await fetchUsername(userId);
        const onlineObject = await fetchOnline(userId);
        resolve({ ...usernameObject, ...onlineObject });
    })
})
Promise.all(promises).then(response => console.log(response));
};

In addition to the other answer and comments about populating the promises array and not wrapping it in another array [promises] :除了关于填充promises数组而不将其包装在另一个数组[promises]中的其他答案和评论:

using async/await in new Promise is anti-pattern, but I have no idea how I can combine the results of the 2 promises to 1 object.在新的 Promise 中使用 async/await 是反模式,但我不知道如何将 2 个 promise 的结果结合到 1 个 object。

This is a convenient use case for Array#map with an async callback.这是带有异步回调的Array#map的一个方便用例。 If you mark the callback async, it automatically returns a Promise that will resolve with the return value.如果您将回调标记为异步,它会自动返回一个 Promise,它将使用返回值进行解析。 So you can write it like this:所以你可以这样写:

const promises = userIds.map(async userID => {
    const usernameObject = await fetchUsername(userId);
    const onlineObject = await fetchOnline(userId);
    return { ...usernameObject, ...onlineObject };
});

Promise.all(promises).then(response => console.log(response));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM