简体   繁体   English

承诺链执行不正常

[英]Promise chain executing out of order

Account.findByOwnerID(userID)
.then(function(account) {
    return validateTo(account, userID);
})
.then(User.findByUsername(email))

In this case, findByOwnerID runs, but as soon as the Promise.all() inside of it starts running, findByUsername starts being executed, skipping over validateTo. 在这种情况下,findByOwnerID将运行,但是其中的Promise.all()开始运行时,将立即开始执行findByUsername,而跳过validateTo。

A simple change in the code makes it all work how I'd expect. 只需对代码进行简单的更改,就可以按照我的期望正常工作。

Account.findByOwnerID(userID)
.then(function(account) {
    return validateTo(account, userID);
})
.then(function() {
    return User.findByUsername(email);
})

Using this code, findByOwnerID runs, then when it resolves, validateTo runs. 使用此代码,findByOwnerID运行,然后在解析时运行validateTo。 When that resolves, findByUsername is ran. 解决后,将运行findByUsername。

So why does this work and not the one above? 那么为什么这项工作可行,而不是上述一项? The way I understood promise chaining was that each .then() expected to be given a promise, which when resolved, will trigger the next .then(). 我理解诺言链接的方式是,每个期望被赋予一个诺言的.then()在解决时都会触发下一个.then()。

Some background on the functions used (I can give more details in these if needed) 使用的功能的一些背景知识(如果需要,我可以在其中提供更多详细信息)

Account.findByOwnerID and User.findByUsername are functions that return a promise. Account.findByOwnerID和User.findByUsername是返回承诺的函数。 Inside of that promise they use Promise.all.then(function() {resolve()}, to return the main promise and continue the chain. 在该承诺中,他们使用Promise.all.then(function(){resolve()})返回主要承诺并继续执行链。

validateTo is a function that returns a promise. validateTo是一个返回承诺的函数。

This has nothing to do with promises. 这与诺言无关。 It's simple function invocation. 这是简单的函数调用。

You're effectively asking why a(b()) behaves differently than a(function () { b() }) . 您实际上是在问a(b())行为为何不同于a(function () { b() }) The simple answer is that in the first, b() is executed and then the result is passed to a() , while in the second, a() executes and is passed a function that may or may not be invoked at some point in the future. 一个简单的答案是,首先执行b() ,然后将结果传递给a() ,而在第二个实施中, a()执行并传递一个函数,该函数可能会或可能不会在未来。

.then(b()) invokes b immediately, and the return value (whatever that may be) is passed into then . .then(b())立即调用b ,然后将返回值(无论是什么值)传递给then This is what your first case does. 这是您的第一种情况。

.then(function () { b() }) passes a function into then . .then(function () { b() })将一个函数传递给then It's up to then to decide when/if to execute that function. then由您决定何时/是否执行该功能。 This is what your second case does. 这是第二种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM