Created
April 9, 2019 13:49
-
-
Save tranduclinh2067/a7e884303fa6d6c66aa47166183aa490 to your computer and use it in GitHub Desktop.
Xử lý bất đồng bộ thông qua Promise (ES6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var time = function(length) { | |
return new Promise (function (resolve, reject) { | |
setTimeout(function () { | |
if(length > 10000) { | |
reject ('Quá lâu để chờ đợi! \n Thời gian thực hiện là ' + length/1000 + ' giây!'); | |
} | |
else { | |
resolve ('Thời gian thực hiện ' + length/1000 + ' giây!'); | |
} | |
}, length); | |
}); | |
} | |
time (5000).then(function(val) { | |
console.log('Có vẻ yêu cầu đã thành công! ' + val); | |
}).catch (function (val) { | |
console.log('ERROR !!! ' + val); | |
}); | |
time (3000).then(function(val) { | |
console.log('Có vẻ yêu cầu đã thành công! ' + val); | |
}).catch (function (val) { | |
console.log('ERROR !!! ' + val); | |
}); | |
time (1000).then(function(val) { | |
console.log('Có vẻ yêu cầu đã thành công! ' + val); | |
}).catch (function (val) { | |
console.log('ERROR !!! ' + val); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
new Promise(function(resolve, reject) { ... } );
-Khi xử lý yêu cầu từ file lớn hoặc gửi yêu cầu lên SERVER đa số đều rất tốn thời gian.
Thay vì chờ đợi xử lý xong, ta có thể nhờ promise làm các vấn đề tiếp theo sau đó mà không phải chờ đợi.