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

时间:2018-11-04 16:31:52

标签: javascript mongodb promise settimeout

我刚刚尝试从递归setTimeout调用异步mongo函数(updateAdded)。但是,我发现了一个上下文错误: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 个答案:

答案 0 :(得分:0)

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

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 });
        })
    });
}