Promise 实现方法(请求)的异步(串行)执行

阅读: 评论:0

Promise 实现方法(请求)的异步(串行)执行

Promise 实现方法(请求)的异步(串行)执行

在项目的实际操作中会用到串行调用方法的情况,实现异步执行,例如
有三个方法,方法一、方法二、方法三,需要执行完方法一之后执行方法二,执行完方法二之后执行方法三,这样的串行的执行顺序可以用层层嵌套的方法来实现,但是这样的话方法嵌套的深看起来就很麻烦,可以用Promise实现,简单的模拟做法如下:

function fourO() {return new Promise(function(resolve, reject) {setTimeout(function(){console.log(44444);resolve();}, 1500);});
}function threeO(){return new Promise(function(resolve, reject) {console.log(333);resolve(123);});
}function twoO(){return new Promise(function(resolve, reject) {console.log(222);resolve();});
}function oneO(){return new Promise(function(resolve, reject) {console.log(111);resolve();});
}
var p = new Promise(function(resolve, reject) {resolve();
});p.then(oneO)
.then(fourO)
.then(twoO)
.then(threeO)
.then(function(result) {console.log('Got value: 最后执行' + result);
});

执行结果如下:

11111
44444
22222
33333
Got value: 最后执行123

用方法fourO模拟接口的调用返回的时间差,这样可以控制实际运用中方法的调用的顺序。

另一种合成用一个Promise对象的方法:

function one(){console.log(11111);
}function two(){console.log(22222);
}function three(){console.log(33333);
}
function fiveP(func){return new Promise(function(resolve, reject) {func();resolve();});
}p.then(fiveP(one))
.then(fiveP(three))
.then(fiveP(two))
.then(function(result) {console.log('Got value: 最后执行' + result);
});

执行结果为:

11111
33333
22222
Got value: 最后执行

记录一下,方便使用。

本文发布于:2024-02-05 06:44:32,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170726570364016.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:方法   Promise
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23