承诺链不按顺序执行

Ell*_*iot 1 javascript promise es6-promise

Account.findByOwnerID(userID)
.then(function(account) {
    return validateTo(account, userID);
})
.then(User.findByUsername(email))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,findByOwnerID会运行,但只要它内部的Promise.all()开始运行,findByUsername就会开始执行,跳过validateTo.

代码中的一个简单更改使我可以按预期工作.

Account.findByOwnerID(userID)
.then(function(account) {
    return validateTo(account, userID);
})
.then(function() {
    return User.findByUsername(email);
})
Run Code Online (Sandbox Code Playgroud)

使用此代码,findByOwnerID运行,然后当它解析时,validateTo运行.解析后,运行findByUsername.

那为什么这个工作而不是上面那个?我理解承诺链接的方式是每个.then()预期会得到一个承诺,当解决时,将触发下一个.then().

关于所用函数的一些背景知识(如果需要,我可以提供更多详细信息)

Account.findByOwnerID和User.findByUsername是返回promise的函数.在该承诺内部,他们使用Promise.all.then(function(){resolve()}来返回主要承诺并继续链.

validateTo是一个返回promise的函数.

mea*_*gar 7

这与承诺无关.这是简单的函数调用.

你有效地问为什么a(b())表现不同于a(function () { b() }).简单的答案是,在第一个,b()执行然后结果传递给a(),而在第二个,a()执行并传递一个函数,可能会或可能不会在将来的某个时候调用.

.then(b())b立即调用,并返回值(无论可能是什么)then.这是你的第一个案例.

.then(function () { b() })将函数传递给then.由... then决定何时/是否执行该功能.这是你的第二个案例.