Js Promise实现异步代码同步执行2
/**
* Created by kikop on 2018/11/3.
*/
$(function () {
execAsyncMethod().then(
execTerminalMethodOnAsyncSucc,
execTerminalMethodOnAsyncFail).then(function (skyResponseResult) {
//成功的处理方法
console.log(new Date() + JSON.stringify(skyResponseResult));
}, function (skyResponseResult) {
//失败的处理方法
console.log(new Date() + JSON.stringify(skyResponseResult));
});
/**
* 执行异步方法
*/
function execAsyncMethod() {
console.log('[execAsyncMethod]' + new Date());
//函数中返回 Promise对象
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log('[execAsyncMethod-do]' + new Date());
var skyRequestRaramsSucc = {"opResult": 'succ'};
var skyRequestRaramsFail = {"opResult": 'fail'};
//测试调用后续方法
//resolve(skyRequestRaramsSucc);
reject(skyRequestRaramsFail);
}, 2000);
});
}
/**
* 执行异步成功方法
* @param skyRequestRarams
*/
function execTerminalMethodOnAsyncSucc(skyRequestRarams) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log('[execTerminalMethodOnAsyncSucc]' + new Date() + JSON.stringify(skyRequestRarams));
skyRequestRarams.goto = "gogo";
resolve(skyRequestRarams);
}, 2000);
});
}
/**
* 执行异步失败方法
* @param skyRequestRarams
*/
function execTerminalMethodOnAsyncFail(skyRequestRarams) {
return new Promise(function (resolve, reject) {
//结束操作
console.log('[execTerminalMethodOnAsyncFail]' + new Date() + JSON.stringify(skyRequestRarams));
reject(skyRequestRarams);
});
}
});