【发布时间】:2018-01-13 01:25:45
【问题描述】:
我有多个具有自己的 setTimeOut 值的回调函数。当我尝试依次运行时,具有最短 setTimeOut 值的那个会首先呈现,即使它被称为最新的也是如此。
有类似的问题(如this、this 和this),但当每个函数都有自己的内部 setTimeout 值时,它们的答案就不起作用。
什么是最好的方法(使用纯 JS)强制函数等待(或确保前一个完成运行)直到前一个完成,而不使用额外的 setTimeOut?
代码:
function NumSequences(){};
NumSequences.prototype.one = function one(callback) {
setTimeout(function() {
callback()
console.log('one');
}, 1000);
};
NumSequences.prototype.two = function two(callback) {
setTimeout(function() {
callback()
console.log('two');
}, 500);
};
NumSequences.prototype.three = function three(callback) {
setTimeout(function() {
callback()
console.log('three');
}, 200);
};
var numSequences = new NumSequences();
function countNow(){};
var promise = new Promise(function(resolve) {
resolve(numSequences.one(countNow));
});
promise.then(function() {
return numSequences.two(countNow);
}).then(function() {
return numSequences.three(countNow);
});
结果:
three //coming first because the function three has the shortest setTimeout value
two
one //coming at last despite being called first
结果应该是:
one
two
three
链接到JSBin
【问题讨论】:
标签: javascript promise synchronous