为什么我的JavaScript使用很长时间才能运行



我正在使用 Cloud Functions for Firebase,我的一些函数超时了。我对 JavaScript 很陌生。看起来我需要在承诺中加入for,我遇到了一些问题。代码实际上太早了,我认为他在很长一段时间内才做到这一点。你有没有办法改进这段代码,让代码更快?

exports.firebaseFunctions = functions.database.ref("mess/{pushId}").onUpdate(event => {
    //first i get event val and a object inside a firebase
    const original = event.data.val();
    const users = original.uids; // THIS ITS ALL USERS UIDS!!
    // so fist i get all users uids and put inside a array
    let usersUids = [];
    for (let key in users) {
        usersUids.push(users[key]);
    }
    // so now i gonna make a promise for use all this uids and get token's device 
    //and save them inside a another child in firebase!!
    return new Promise((resolve) => {
            let userTokens = [];
            usersUids.forEach(element => {
                admin.database().ref('users/' + element).child('token').once('value', snapShot => {
                    if (snapShot.val()) { // if token exist put him inside a array
                        userTokens.push(snapShot.val());
                    }
                })
            })
            resolve({
                userTokens
            })
        }) // now i make then here, from get userTokens and save in another child inside a firebase database
        .then((res) => {
            return admin.database().ref("USERS/TOKENS").push({
                userTokens: res,
            })
        })
})

您正在使用Firebase发出网络请求,所以也许这就是它很慢的原因。您为每个用户发出一个请求,因此,如果您那里有 100 个 ID,则可能需要一段时间。

但是我注意到另一个问题,那就是:你只是解析为一个空列表。若要等待多个承诺,请创建一个承诺数组,然后使用 Promise.all 创建一个并行等待所有承诺的承诺。

当你调用 resolve 时,你已经完成了 forEach,并且你已经开始了每个承诺,但它们还没有被添加到列表中。为了让它变得更好,把它带到一个map并收集所有返回的承诺,然后返回Promise.all.

最新更新