feat(Xapi#watchTask): returns a promise which settled when the task finishes

This commit is contained in:
Julien Fontanet 2017-06-08 12:19:08 +02:00
parent 7e2bd52f25
commit 22c515b0e7

View File

@ -9,6 +9,7 @@ import { filter, forEach, isArray, isObject, map, noop, reduce, startsWith } fro
import { import {
cancelable, cancelable,
catchPlus as pCatch, catchPlus as pCatch,
defer,
delay as pDelay delay as pDelay
} from 'promise-toolbox' } from 'promise-toolbox'
@ -158,6 +159,8 @@ export class Xapi extends EventEmitter {
this._objectsByRefs = createObject(null) this._objectsByRefs = createObject(null)
this._objectsByRefs['OpaqueRef:NULL'] = null this._objectsByRefs['OpaqueRef:NULL'] = null
this._taskWatchers = Object.create(null)
this.on('connected', this._watchEvents) this.on('connected', this._watchEvents)
this.on('disconnected', () => { this.on('disconnected', () => {
this._fromToken = '' this._fromToken = ''
@ -370,6 +373,22 @@ export class Xapi extends EventEmitter {
) )
} }
watchTask (ref) {
const watchers = this._taskWatchers
if (watchers === undefined) {
throw new Error('Xapi#watchTask() requires events watching')
}
// allow task object to be passed
if (ref.$ref !== undefined) ref = ref.$ref
let watcher = watchers[ref]
if (watcher === undefined) {
watcher = watchers[ref] = defer()
}
return watcher.promise
}
get pool () { get pool () {
return this._pool return this._pool
} }
@ -470,6 +489,19 @@ export class Xapi extends EventEmitter {
if (type === 'pool') { if (type === 'pool') {
this._pool = object this._pool = object
} else if (type === 'task') {
const taskWatchers = this._taskWatchers
let taskWatcher = taskWatchers[ref]
if (taskWatcher !== undefined) { // no need to check for object type
const { status } = object
if (status === 'success') {
taskWatcher.resolve(object.result)
delete taskWatchers[ref]
} else if (status === 'failure') {
taskWatcher.reject(object.error_info)
delete taskWatchers[ref]
}
}
} }
} }