创造诺言
在一个节点控制器方法中,我有这个代码块,我想在继续进行下一个代码之前 。我该怎么做?
我认为这应该是通过承诺(该控制器方法中唯一的一个)来完成的,并尝试了以下代码。但这会生成以下错误。我在做什么错?
typeError:对象是不可能的(无法读取属性 符号(符号。术语))
const other = new Promise(async function () {
updatedFields.last_login_at = newDateNow();
if (updatedFields.isActivated) {
updatedFields.activated_at = newDateNow();
updatedFields.deactivated_at = null;
} else if (updatedFields.isActivated === false) {
updatedFields.deactivated_at = newDateNow();
updatedFields.activated_at = null;
}
});
await Promise.all(other);
... only when the Promise is completed, continue with the rest of the code
Inside a Node controller method I have this code block that I would like to await
for before continuing with the code that comes next. How can I do this?
I thought this should be done with a Promise (the only one in that controller method) and have tried the code below. But this generates the error below. What am I doing wrong?
TypeError: object is not iterable (cannot read property
Symbol(Symbol.iterator))
const other = new Promise(async function () {
updatedFields.last_login_at = newDateNow();
if (updatedFields.isActivated) {
updatedFields.activated_at = newDateNow();
updatedFields.deactivated_at = null;
} else if (updatedFields.isActivated === false) {
updatedFields.deactivated_at = newDateNow();
updatedFields.activated_at = null;
}
});
await Promise.all(other);
... only when the Promise is completed, continue with the rest of the code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将以相反的顺序分解。
首先,
promise.all()
用于等待多个承诺,因此,您可以做
第二个问题,即通常应该避免
new Promise
。它在您的情况下是错误的,您也不应使用async
函数新的Promise
,这是没有意义的。这简化为:下一个问题是您在此功能中没有做任何实际利用异步/等待/承诺的任何事情,因此您实际上应该摆脱
async
和在这些情况下等待
。这样可以将您的代码段减少到:
I'm going to break this down in reverse order.
First,
Promise.all()
is for waiting for multiple promises, so instead of:You can just do
The second issue is that you should usually avoid
new Promise
. It's used incorrectly in your case, and you also shouldn't useasync
functions insidenew Promise
, it makes no sense. That simplifies it to:The next issue is that you're not doing anything in the this function that actually takes advantage of async/await/promises, so you should really just get rid of
async
andawait
for these cases.That reduces your code snippet to:
当建立承诺时,其状态将在等待中,当您等待它时,它会等到它被拒绝或解决。由于您没有解决或拒绝,因此它行不通。另外,Promise.All函数的第一个参数应该是数组
When a promise is created, its state is pending, and when you await it, it waits until it is rejected or resolved. Since you don't resolve or reject, it does not work. Also, Promise.all function's first argument should be an array