【发布时间】:2017-01-22 15:44:23
【问题描述】:
我想创建一个示例来了解Promise().then()。
我创建了一个需要时间并且必须同步完成的操作。
代码如下:
// Example: long operation that takes time to execute
var longOperation = function(id) {
var time = 1000 * Math.random();
console.log('[' + id + '] Operation started for: ' + time + 'ms');
setTimeout(function(err) {
console.log('[' + id + '] Completed operation: ' + time + 'ms');
var count = id * 10;
}, 1000 * Math.random());
};
// Create new promise for longOperation
var longOpPromise = function(id) {
return new Promise(function(resolve, reject) {
longOperation(id);
resolve(null);
});
};
// Create sequencing
var runLongOperation = function(callback) {
var count1;
longOpPromise(1).then(function(count) {
count1 = count;
console.log('Count 1: ' + count1);
longOpPromise(2).then(function(count2) {
console.log('Count 2: ' + count2);
callback(null, count1, count2);
});
});
};
// Run
runLongOperation(function(err, count1, count2) {
if (err) console.error(err);
console.log('Count 1 ' + count1 + ' | Count 2: ' + count2);
});
运行结果:
**** Output ****
[1] Operation started for: 626.77225866355ms
[1] Completed operation: 626.77225866355ms
then() 中的方法不执行,回调也不执行。也许计数没有得到解决。
如果我将其更改为resolve(null),这些会执行但不按顺序执行:
**** Output ****
[1] Operation started for: 435.5367429088801ms
Count 1: null // This should come after [1] is completed
[2] Operation started for: 256.17250707000494ms
Count 2: null // This should come after [2] is completed
Count 1 null | Count 2: null // This should come after [2] is completed
[2] Completed operation: 256.17250707000494ms
[1] Completed operation: 435.5367429088801ms
感谢您的帮助。
【问题讨论】:
标签: javascript