有什么区别:
新承诺(函数(res, rej) {
res(“aaa”);
})
不要犹豫(函数(结果){
返回" bbb ";//直接返回字符串
})
不要犹豫(函数(结果){
console.log(结果);
});
这:
new Promise(function(res, rej) {
res(“aaa”);
})
.then(function(result) {
返回 Promise.resolve(“bbb”);返回承诺
})
.then(function(result) {
控制台.log(结果);
});
我问,因为我得到了不同的行为使用Angular和$http服务链接.then()。代码有点多,所以首先是上面的例子。
The rule is, if the function that is in the then handler returns a value, the promise resolves/rejects with that value, and if the function returns a promise, what happens is, the next then clause will be the then clause of the promise the function returned, so, in this case, the first example falls through the normal sequence of the thens and prints out values as one might expect, in the second example, the promise object that gets returned when you do Promise.resolve("bbb")'s then is the then that gets invoked when chaining(for all intents and purposes). The way it actually works is described below in more detail.
引用承诺/A+规范:
The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.
This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.
这里需要注意的关键是这一行:
如果x是一个承诺,采用它的状态[3.4]
链接:https://promisesaplus.com/ # point-49
你已经得到了一个很好的正式答案。我想我应该加一个简短的。
以下几点与Promises/A+ Promises相同:
要求的承诺。resolve(在Angular中是$q.when)
调用承诺构造函数并在其解析器中解析。在你的例子中,这是新的q。
从then回调返回一个值。
要求的承诺。都在一个有值的数组上,然后提取那个值。
因此,对于承诺值或普通值X,下面这些都是相同的:
Promise.resolve(x);
new Promise(function(resolve, reject){ resolve(x); });
Promise.resolve().then(function(){ return x; });
Promise.all([x]).then(function(arr){ return arr[0]; });
毫无疑问,承诺规范是基于承诺解决过程的,它支持库之间的简单互操作(如$q和本机承诺),并使您的生活总体上更简单。无论何时出现承诺解决方案,解决方案都会产生整体一致性。