graphenejs-lib
graphenejs-lib copied to clipboard
FetchChain can resolve into a string object or an error object when rejected
For the current implementation of FetchChain, it will throw an error object when the method doesn't exist. However, when it is timeout, it will be resolved to "timeout" string. Which mean in the catch function of the Promise, it is possible to get either Error object or string object. How about make it consistent?
function FetchChain(methodName, objectIds, timeout = 1900) {
let method = chain_store[methodName]
if( ! method ) throw new Error("ChainStore does not have method " + methodName)
let arrayIn = Array.isArray(objectIds)
if( ! arrayIn ) objectIds = [ objectIds ]
return chain_store.FetchChainObjects(method, Immutable.List(objectIds), timeout)
.then( res => arrayIn ? res : res.get(0) )
}
function FetchChainObjects(method, object_ids, timeout) {
let get_object = method.bind(chain_store);
return new Promise((resolve, reject) => {
let timeout_handle = null;
function onUpdate(not_subscribed_yet = false) {
let res = object_ids.map(id => get_object(id));
if (res.findIndex(o => o === undefined) === -1) {
if(timeout_handle) clearTimeout(timeout_handle);
if(!not_subscribed_yet) chain_store.unsubscribe(onUpdate);
resolve(res);
return true;
}
return false;
}
let resolved = onUpdate(true);
if(!resolved) chain_store.subscribe(onUpdate);
if(timeout && !resolved) timeout_handle = setTimeout(() => {
chain_store.unsubscribe(onUpdate);
reject("timeout");
}, timeout);
});
}