Last active
March 31, 2021 07:37
-
-
Save ronen-e/1d4197803067c7f0db28c595699d8ffa to your computer and use it in GitHub Desktop.
asynchronous task queue using Vue instances to keep the data
This file contains hidden or 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
function newData(options = {}) { | |
var data = Object.assign({ | |
sort: 'date+', | |
}, options, { queue: [] }) | |
return data; | |
} | |
function delay(timeout = 0) { | |
return new Promise((resolve, reject) => setTimeout(resolve, timeout)); | |
} | |
var Task = Vue.extend({ | |
data: () => Object.assign(newData()), | |
methods: { | |
copy(){ return new Task({ data: newData(this.$data) }) }, | |
newTask(task = {}) { | |
task.copy = task.copy || this.copy(); | |
task.id = task.id || ++Task.count; | |
task.promise = delay(1000) | |
.then(() => {task.initial = true; return task; }) | |
.then(this.sendData) | |
.then(() => {task.sendData = true; return task; }) | |
.then(this.removeTask) | |
.catch(() => this.handleError(task)) | |
return task; | |
}, | |
handleError(task) { | |
task.errorCounter = task.errorCounter || 0; | |
task.errorCounter++; | |
if (task.errorCounter < 5) { | |
console.warn('retry task', task) | |
this.newTask(task); | |
} else { | |
console.error('task errored out', task) | |
this.removeTask(task) | |
} | |
}, | |
sendData(task) { | |
return delay(1000).then(() => task) | |
}, | |
process() { | |
this.addTask(this.newTask()) | |
}, | |
addTask(task) { | |
this.queue.push(task); | |
}, | |
removeTask(task) { | |
this.queue = this.queue.filter(item => item != task); | |
return task; | |
} | |
} | |
}); | |
Task.count = 0; | |
var vm = new Task(); | |
vm.sort = 'test 1'; | |
vm.process(); | |
vm.sort = 'test 2'; | |
vm.process(); | |
vm.sort = 'test 3'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment