从递归超时调用异步 mongodb 函数,我想是上下文错误
Posted
技术标签:
【中文标题】从递归超时调用异步 mongodb 函数,我想是上下文错误【英文标题】:Calling async mongodb function from recursive timeout, context error i suppose 【发布时间】:2019-04-08 03:14:09 【问题描述】:我刚刚尝试从递归 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)
,但没有解决问题。
【问题讨论】:
不要将async function
传递给setTimeout
,因为没有任何东西可以处理返回的promise 中的错误。相反,承诺setTimeout
,然后使用while (true) await delay(3000); …
。
谢谢你)我该死的:)
【参考方案1】:
由于缺点,我可以理解我不是一个好的编码器,但也许有人比我更愚蠢,所以我在这里发布最合适的解决方案:
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 );
)
);
【讨论】:
以上是关于从递归超时调用异步 mongodb 函数,我想是上下文错误的主要内容,如果未能解决你的问题,请参考以下文章
从图库中选择照片(onActivityResult()问题 - 我想是这样) - 片段Android