Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / common / extensions / docs / server2 / future.py
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 import sys
6
7 _no_value = object()
8
9
10 def Collect(futures, except_pass=None):
11   '''Creates a Future which returns a list of results from each Future in
12   |futures|. |except_pass| should be one or more exceptions to ignore when
13   calling Get on the futures.
14   '''
15   def resolve():
16     resolved = []
17     for f in futures:
18       try:
19         resolved.append(f.Get())
20       # "except None" will simply not catch any errors
21       except except_pass:
22         pass
23     return resolved
24   return Future(callback=resolve)
25
26
27 class Future(object):
28   '''Stores a value, error, or callback to be used later.
29   '''
30   def __init__(self, value=_no_value, callback=None, exc_info=None):
31     self._value = value
32     self._callback = callback
33     self._exc_info = exc_info
34     if (self._value is _no_value and
35         self._callback is None and
36         self._exc_info is None):
37       raise ValueError('Must have either a value, error, or callback.')
38
39   def Get(self):
40     '''Gets the stored value, error, or callback contents.
41     '''
42     if self._value is not _no_value:
43       return self._value
44     if self._exc_info is not None:
45       self._Raise()
46     try:
47       self._value = self._callback()
48       return self._value
49     except:
50       self._exc_info = sys.exc_info()
51       self._Raise()
52
53   def _Raise(self):
54     exc_info = self._exc_info
55     raise exc_info[0], exc_info[1], exc_info[2]