Ris*_*ari 6 javascript node.js promise jquery-deferred q
我试图理解为什么以下代码与Q.defer()和Promise()的行为不同
案例1:当我使用Q.defer()时
getDocument(id)
.then(function (response) {
console.log('in first then')
return 'from two';
}).then(function (response) {
console.log(response)
});
var getDocument=function(){
var b = Q.defer();
b.resolve('from getDocument'); // here will do some async operation..this is just an example
return b.promise;
}
Run Code Online (Sandbox Code Playgroud)
输出:
in first then
undefined
Run Code Online (Sandbox Code Playgroud)
案例2:使用Promise()
getDocument(id)
.then(function (response) {
console.log('in first then')
return 'from two';
}).then(function (response) {
console.log(response)
});
var getDocument=function(){
return Promise.resolve('from getDocument');
}
Run Code Online (Sandbox Code Playgroud)
输出:
in first then
from two
Run Code Online (Sandbox Code Playgroud)
题
事实上,两个示例都返回相同的结果(相同的顺序)。检查这个 codepen示例
\n\nvar getDocument=function(){\n var b = Q.defer();\n b.resolve(\'Q from getDocument\'); // here will do some async operation..this is just an example\n return b.promise;\n}\n\ngetDocument(1)\n.then(function (response) {\n console.log(\'Q in first then\')\n return \'Q from two\';\n}).then(function (response) {\n console.log(response)\n});\n\nvar getDocumentP=function(){\n return Promise.resolve(\'P from getDocument\');\n}\n\ngetDocumentP(1)\n.then(function (response) {\n console.log(\'P in first then\')\n return \'P from two\';\n}).then(function (response) {\n console.log(response)\n});\nRun Code Online (Sandbox Code Playgroud)\n\n2) 你可以在这里看到 Q.defer 的一些用法:Q.defer you\xc2\xb4re 做错了
\n| 归档时间: |
|
| 查看次数: |
3396 次 |
| 最近记录: |