Skip to content

Instantly share code, notes, and snippets.

@joecliff
Last active August 29, 2015 13:58
Show Gist options
  • Save joecliff/9927050 to your computer and use it in GitHub Desktop.
Save joecliff/9927050 to your computer and use it in GitHub Desktop.
使用promise(q.js)时函数可能的返回值
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