我想創建一個例子來理解Promise().then()
。 我創建了一個需要時間並且必須同步完成操作的操作。 該代碼是下面:Javascript Promise/Then Example
// 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
感謝您的幫助。