答应麻烦!我怎样才能以等待结束的方式写这个?

Promise trouble! How can I write this in such a way that it waits for the end?

尝试以等待数据库操作完成的方式编写此代码。可能吗?

function addFriendsToSession(session, sessionId) {
    const friends = [];

    const incoming = session.users.forEach(async user => {
        console.log('user', user);
        await db
            .collection('users/' + user + '/settings')
            .doc(user)
            .get()
            .then(doc => {
                if (doc.exists) {
                    const returnObj = doc.data();
                    return returnObj.friends ? returnObj.friends : [];
                } else {
                    return [];
                }
            });
    });
    friends.push(incoming);
    return friends;
}

使用Promise.all.

Promise.all 接受一系列承诺,并在每个承诺已解决后解决。您可以使用 map 映射您的操作。例如,

const promises = session.users.map(user => {
    console.log('user', user);
    return db
        .collection('users/' + user + '/settings')
        .doc(user)
        .get()
        .then(doc => {
            if (doc.exists) {
                const returnObj = doc.data();
                return returnObj.friends ? returnObj.friends : [];
            } else {
                return [];
            }
        });
});

const friends = await Promise.all(promises)

return friends;

这里有很多问题。

  1. db.then() 中,使用了 return,但是这个值永远不会从包含它的函数(即 async user => {...})中 return 编辑
  2. const incoming 被赋予 session.users.forEach 的结果,但是 Array.forEach() 从来没有 return 值(你可能在想 Array.map()?)
  3. 即使你解决了前两个问题,incoming 仍然是一个 Promises 数组

补充建议:

  • 不要将 async/await 与 .then
  • 混用

综合起来:

const incoming = session.users.map(async user => {
    console.log('user', user);
    const doc = await db
        .collection('users/' + user + '/settings')
        .doc(user)
        .get();
        //we assigned `doc` using await instead of using .then
    if (doc.exists) {
        const returnObj = doc.data();
        return returnObj.friends ? returnObj.friends : [];
    } else {
        return [];
    }
});
//incoming is not an array of Promises
const incomingFriends = await Promise.all(incoming); //takes an array of Promises and returns an array of the resolved values
//incomingFriends is now an array of friends

//next line would make the last element an array
//friends.push(incoming); 
//you probably want to push every element of the array
friends.push(...incomingFriends);