代码之家  ›  专栏  ›  技术社区  ›  Dima

从递归超时调用异步mongodb函数,我想是上下文错误

  •  -5
  • Dima  · 技术社区  · 7 年前

    setTimeout . 但是我发现了一个上下文错误: UnhandledPromiseRejectionWarning: MongoError: Topology was destroyed

    async function updateAdded(followersToAdd, username = 'blower1223', db = amng){
        const lel = await db.find({collection:COLLECTION, where: {username: username}});
        const all = await lel[0].followersAdded + followersToAdd;
        await amng.update({
            collection: COLLECTION,
            where: { username: username },
            row: { followersAdded: all }
        })
    }
    
    await amng.connect();
    const loginInfo = await amng.find({ collection: COLLECTION }, {});
    console.log(loginInfo);
    let temp = [];
    loginInfo.map((user) => {
        temp.push(new Instagram({ username: user.username, password: user.password }))
    });
    const users = temp;
    temp = [];
    let that = this;
    
    
    let timerId = setTimeout(async function approveSession() {
        for (let i = 0; i < users.length; i++) {
            const client = users[i];
            await client.login();
            const req = await client.getFollowRequests();
            console.log(req);
            await updateAdded(req.length); 
            for (let i = 0; i < req.length; i++) {
                const elem = req[i];
                await client.approve({ userId: elem.node.id });
            }
        } 
        timerId = setTimeout(approveSession, 3000);
    }, 3000);
    

    我试着用 updateAdded.call(that, req.length) ,但没有解决问题。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Dima    7 年前

    因为这些缺点,我可以理解我不是一个好的程序员,但也许有人比我更蠢,所以我在这里发布了最合适的解决方案:

    function promisifiedDelay(delay) {
        return new Promise(function (fulfill) {
            setTimeout(fulfill, delay)
        })
    }
    while (true) {
        await promisifiedDelay(3000);
        users.map(async(client) => {
            await client.login();
            const requests = await client.getFollowRequests();
            console.log(requests);
            await updateAdded(requests.length, await client.getCurUsername());
            requests.map(async(request) => {
                await client.approve({ userId: request.node.id });
            })
        });
    }