我需要以某种方式遍历work
传递给该数组的数组,_start
然后对于数组中的每个项目,我都需要以某种方式调用具有相同名称的相应函数。
我无法控制work
数组中的项目数或项目数,我知道总是会有相应的功能。
我不想同时调用所有函数,一旦第一个函数在3秒后解析,我便要调用第二个函数,一旦第二个函数在3秒后解析,我便要调用第三个函数。一旦第三个函数在另一个3秒钟后解析,我想调用_done()。
在此示例中,每个函数需要3秒钟才能完成_done
9秒钟的调用。
function _start(data){
// Insert some kinda native magic loop
}
function _one(){
return new Promise((resolve, reject) => {
setTimeout(function(){
resolve(1);
}, 3000);
})
};
function _two(){
return new Promise((resolve, reject) => {
setTimeout(function(){
resolve(2);
}, 3000);
})
};
function _done(){
console.log('All done in 9 seconds)
}
(function(){
var work = ['_one', '_two', '_two'];
_start(work);
})();
给定顺序由数组指定,您可以使用reduce将promise聚合到一个链中
const _start = (...actions) => {
return actions.reduce((chain, action) => {
const func = this[action];
return chain.then(() => func());
}, Promise.resolve());
}
...
_start('_one', '_two', '_three').then(() => console.log('All done'));
看到它在行动-例子追加额外then
的链只是为了输出的承诺的任何结果(可能outwith这个问题,但你可能有,如果让数据传回需要考虑的东西的范围)。
更新资料
可以看到您打算_start
从声明函数的其他上下文中调用,这很好,但是您需要确保事先设置正确的上下文,即
const self = this;
(function() {
_start.bind(self)('_one', '_two', '_two');
})();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句