unicloud-co-task.js 950 字节
Newer Older
DCloud_JSON's avatar
1.0.21  
DCloud_JSON 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
class Task {
	constructor({
		success,
		fail,
		complete
	} = {}) {
		this.status = 0
		this.callback = {
			success,
			fail,
			complete
		}
	}
	invoke(callbackName, ...args) {
		if (this.status !== 0) {
			// console.log('此任务已被终止');
			return
		}
		const callback = this.callback[callbackName]
		callback && callback(...args)
	}
	abort() {
		this.status = 1
	}
}

export default function main({
	coName,
	funName,
	param,
	success,
	fail,
	complete,
	config
} = {}) {
	
	if(!Array.isArray(param)){
		throw new Error('param的值必须为数组')
	}
	
	const task = new Task({
		success,
		fail,
		complete
	})

	const uniCloudCo = uniCloud.importObject(coName, config||{})

	uniCloudCo[funName](...param)
		.then(res => {
			task.invoke('success', res)
		})
		.catch(err => {
			task.invoke('fail', err)
		})
		.finally(res => {
			task.invoke('complete', res)
		})
	return task
}