我在辅助函数answerUserTag 中有这个 Waterline 异步调用:
theQuestion = await UserTag.findOne({id: answerObject.tag});
这就是我调用上述助手的方式:
const promises = userTagAnswers.map(userTagAnswer =>
sails.helpers.answerUserTag.with(
{
userTagAnswer: userTagAnswer,
answeringUserId: inputs.userId,
userType: inputs.userType
}));
await Promise.all(promises);
如果只有一个 userTagAnswers(即一个 promise ),它就可以正常工作。但是,如果有两个 userTagAnswers 并且我在帮助程序中的 theQuestion
查询之后设置了一个断点,我会看到以下不合理的值:
answerObject.tag
is equaled to5c338ae267a1983e84340388
theQuestion.id
is equaled to5c27227ac1e60913703f3002
当调用多个 Promise 时,变量之间似乎存在不合逻辑的重叠。
最佳答案
尝试通过 Promise.each()
调试它?由于迭代是连续的,因此您会知道哪个 Promise 困扰着您。
其次,如果您指定辅助函数,那就太好了。
第三,为什么with
?如果您检查MDN - with ,它清楚地说明了并且我引用了:
Use of the
with
statement is not recommended, as it may be the source of confusing bugs and compatibility issues. It has Ambiguity contra. Thewith
statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object.
关于javascript - Promise 和异步函数 "borrowing"来自同时运行的 Promise 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54236816/