Last active
August 29, 2015 13:58
-
-
Save joecliff/9927050 to your computer and use it in GitHub Desktop.
使用promise(q.js)时函数可能的返回值
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Q = require('q'); | |
function createPromise(data) { | |
var deffered = Q.defer(); | |
setImmediate(deffered.resolve.bind(deffered, data)); | |
return deffered.promise; | |
}; | |
/** | |
* 第一步返回必须是promise,否则没有then... | |
*/ | |
function step1() { | |
return createPromise('step1 result'); | |
} | |
/** | |
* 如果内部有调用其他异步操作,除非不关心执行结果,否则务必return promise | |
*/ | |
function step2(param1) { | |
console.log(param1); | |
return step3('call step3 in step2');//这句必须有return | |
// return createPromise('step2 result'); | |
} | |
/** | |
* 中间步骤可以返回非promise结果,包括: 正常js数据类型、空、没有显式return | |
*/ | |
function step3(param1) { | |
console.log(param1); | |
// return; | |
// return 'step3 result'; | |
return createPromise('step3 result'); | |
} | |
step1().then(step2).then(step3) | |
.then(console.log).catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment