Skip to content

Instantly share code, notes, and snippets.

@tranduclinh2067
Created April 9, 2019 13:49
Show Gist options
  • Save tranduclinh2067/a7e884303fa6d6c66aa47166183aa490 to your computer and use it in GitHub Desktop.
Save tranduclinh2067/a7e884303fa6d6c66aa47166183aa490 to your computer and use it in GitHub Desktop.
Xử lý bất đồng bộ thông qua Promise (ES6)
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);
});
@tranduclinh2067
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment