Skip to content

Instantly share code, notes, and snippets.

@qiu8310
Last active December 29, 2015 05:49
Show Gist options
  • Select an option

  • Save qiu8310/7624210 to your computer and use it in GitHub Desktop.

Select an option

Save qiu8310/7624210 to your computer and use it in GitHub Desktop.
example: jquery-deferred-then
/* 三个步骤串连起来了 */
$.Deferred(function (dfd) {
setTimeout(function () {dfd.resolve('step 1');}, 1000);
}).promise()
.then( // then 返回的是个新的 promise 对象
function (arg) {
console.log('finish ' + arg);
return $.Deferred(function (dfd) {
setTimeout(function (){newDfd.resolve('step 2');}, 1000);
}).promise();
}
).then(
function (arg) {
console.log('finish ' + arg);
return $.Deferred(function (dfd) {
setTimeout(function () {newDfd.resolve('step 3');}, 1000);
}).promise();
}
).done(
function (arg) {
console.log('finish ' + arg + ', you finish all steps');
}
);
/* node js 读取文件时,大量使用回调函数 */
/* 1:判断文件是否存在 */
fs.exists('/path/to/some/file', function (exists) {
if (exists) {
/* 2:判断是否是file */
fs.stat('/path/to/some/file', function (err, stats) {
if (stats && stats.isFile()) {
/* 3:最后读取文件 */
fs.readFile('/path/to/some/file', function (err, data) {
if (err) {
// 错误处理:读取文件失败
} else {
// 读取文件成功,处理文件数据 data
}
});
} else {
// 错误处理:不是 file,或文件不可访问
}
});
} else {
// 错误处理:文件不存在
}
});
/* 通过 jQuery 的 Deferred.then 来消除回调,但代码量增加了 */
$.Deferred(function () {
var dfd = $.Deferred();
fs.exists('/path/to/some/file', function (exists) {
if (exists) {
dfd.resolve();
} else {
dfd.reject('文件不存在');
}
});
return dfd.promise();
}).then(function () {
var dfd = $.Deferred();
fs.stat('/path/to/some/file', function (err, stats) {
if (stats && stats.isFile()) {
dfd.resolve();
} else {
dfd.reject('不是 file');
}
}
return dfd.promise();
}).then(function () {
$.Deferred(function (dfd) {
fs.readFile('/path/to/some/file', function (err, data) {
if (err) {
dfd.reject('读取文件失败');
} else {
dfd.resolve(data);
}
});
}).promise();
}).done(function (data) {
console.log('文件数据:' + data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment