在承诺中返回promise和返回undefined之间的区别
我不太清楚这两种常见情况之间的区别。
说我们有这个:
user.save().then(function(val){ anotherPromise1(val); }).then(function(val){ anotherPromise2(val); }).catch(function(err){ });
与:
user.save().then(function(val){ return anotherPromise1(val); }).then(function(val){ return anotherPromise2(val); }).catch(function(err){ });
我知道这有所作为,但究竟如何?
如果你没有从callback中返回一个值,那么你实际上是返回undefined
。 接下来的callback将立即运行,并将undefined
作为分辨率值。
如果你从then
callback中返回一个承诺, then
第二个callback就等待这个承诺(间接的,但是这并不重要),当这个承诺解决时,从这个承诺中获得parsing值。
(这在Promises / A +规范中的规范中有所介绍,但略有遗漏 – 它没有明确提到如果onFulfilled
没有返回任何内容会发生什么,但在JavaScript中,调用一个函数总是给你一个结果值;如果该函数没有显式地返回,那么undefined
就是调用它的结果,JavaScript没有void
方法的概念,就是C / C#/ C ++ / Java。
你可以在Babel的REPL上的脚本中看到它:
let start = Date.now(); function elapsed() { let rv = String(Date.now() - start); while (rv.length < 4) { rv = "0" + rv; } return rv; } function anotherPromise(type, val) { console.log(`${elapsed()}: anotherPromise[${type}] got ${val}`); return new Promise(resolve => { setTimeout(() => { resolve(val * 2); }, 1000); }); } function anotherPromise2(type, val) { console.log(`${elapsed()}: anotherPromise2[${type}] got ${val}`); return new Promise(resolve => { setTimeout(() => { resolve(val * 3); }, 10); }); } let user = { save: () => { return new Promise(resolve => { setTimeout(() => { resolve(42); }, 10); }); } } // Without return user.save().then(function(val){ anotherPromise("without", val); }).then(function(val){ anotherPromise2("without", val); }).then(function() { console.log(`${elapsed()}: All done`); }).catch(function(err){ }); user.save().then(function(val){ return anotherPromise("with", val); }).then(function(val){ return anotherPromise2("with", val); }).then(function() { console.log(`${elapsed()}: All done`); }).catch(function(err){ });
输出是(例如):
0015:另一个[没有]得到了42 0017:anotherPromise2 [没有]没有定义 0018:全部完成 0020:另一个好消息是42 1021:anotherPromise2 [拿到] 84 1032:全部完成
注意没有回报和回报之间的区别:
-
没有 ,
anotherPromise2
立即被调用(正如我们可以看到从经过的时间值),并收到undefined
。 -
随着 ,
anotherPromise2
等待anotherPromise
的决心发生,然后收到84
(anotherPromise
的决议价值)
不同的是在这个问题上的时机。
在示例1中, save
许诺anotherPromise1
并且将调用anotherPromise1
并且由于没有返回的anotherPromise2
将立即调用anotherPromise2
。
如果您返回anotherPromise1
函数的承诺,则在anotherPromise1
解决后,将会发生anotherPromise
的调用。
所以示例1: anotherPromise1
和anotherPromise2
将同时拍摄而示例2: anotherPromise2
将等待anotherPromise1
被parsing