如何获得承诺的价值?
我正在从Angular的$q文档看这个例子,但我认为这可能适用于一般的承诺。 他们有这个例子,逐字抄写他们的评论,包括:
promiseB = promiseA.then(function(result) { return result + 1; }); // promiseB will be resolved immediately after promiseA is resolved and its value // will be the result of promiseA incremented by 1
我不清楚这是如何工作的。 如果我可以调用.then()对第一个.then()的结果进行链接,我知道我可以,那么promiseB是一个Objecttypes的promise对象。 这不是一个Number 。 那么它的意思是“它的价值将会是promiseA增加1的结果”呢?
我应该作为promiseB.value或类似的东西访问? 成功callback如何返回承诺并返回“result + 1”? 我错过了一些东西。
promiseA的then函数返回一个新的promise( promiseB ),在promiseA被parsing后立即parsing,它的值是promiseA成功函数返回的值。
在这种情况下, promiseA用值 – resultparsing,然后立即用result + 1的值parsingpromiseB 。
访问promiseB的值与我们访问promiseA的结果promiseA 。
promiseB.then(function(result) { // here you can use the result of promiseB });
当一个承诺被解决/拒绝时,它会调用它的成功/error handling程序:
var promiseB = promiseA.then(function(result) { // do something with result });
then方法还返回一个promise:promiseB, 根据来自promiseA的成功/error handling程序的返回值将被parsing/拒绝。
有三个可能的值promiseA的成功/error handling程序可以返回将影响promiseB的结果:
1. Return nothing --> PromiseB is resolved immediately, and undefined is passed to the success handler of promiseB 2. Return a value --> PromiseB is resolved immediately, and the value is passed to the success handler of promiseB 3. Return a promise --> When resolved, promiseB will be resolved. When rejected, promiseB will be rejected. The value passed to the promiseB's then handler will be the result of the promise
有了这个理解,你可以理解以下几点:
promiseB = promiseA.then(function(result) { return result + 1; });
然后调用立即返回promiseB。 当promiseA被parsing时,它将把结果传递给promiseA的成功处理器。 由于返回值是promiseA的结果+ 1,所以成功处理程序正在返回一个值(上面的选项2),所以promiseB将立即parsing,并且promiseB的成功处理程序将被传递给promiseA的结果+1。
那么promiseB的函数就会接收到promiseA返回的函数。
这里promiseA返回的是一个数字,在promise的成功函数中可以作为number参数使用。 然后将增加1
parsing评论有点不同于你目前的理解可能会有所帮助:
// promiseB will be resolved immediately after promiseA is resolved
这表明, promiseB是一个承诺,但promiseA解决后立即解决。 看着这个的另一种方法意味着promiseA.then()返回一个被分配给promiseB 。
// and its value will be the result of promiseA incremented by 1
这意味着promiseAparsing的值是promiseB将作为其successCallback值接收的值:
promiseB.then(function (val) { // val is now promiseA's result + 1 });
也许这个小的Typescript代码示例将有所帮助。
private getAccount(id: Id) : Account { let account = Account.empty(); this.repository.get(id) .then(res => account = res) .catch(e => Notices.results(e)); return account; }
这里repository.get(id)返回一个Promise<Account> 。 我将它分配给then语句中的variablesaccount 。