脚本开发

模块 ringo/promise

允许使用将在未来解决的deferred值。

Class Deferred

Instance Methods

Instance Properties

Class Promise

Instance Methods

Class PromiseList


Deferred ()

创建一个代表deferred值的对象。deferred对象有两个属性:一个 promise 对象和一个 resolve() 函数。

promise对象可用于注册promise最终解析时要调用的回调。

resolve函数用于解决promise被执行或失败。

Example

// --- sample output ---
// getDeferredValue() ...
// getDeferredValue() finished after 396 ms
// Resolved promise, got foo
// Total time:  2400 ms

const getDeferredValue = function () {
  const deferred = new Deferred();
  setTimeout(function() {
    deferred.resolve("foo");
  }, 2000);

  return deferred;
};

const start = Date.now();
console.log("getDeferredValue() ... ");

const def = getDeferredValue();
console.log("getDeferredValue() finished after",
  Date.now() - start, "ms");

def.promise.then(function(value) {
  console.log("Resolved promise, got", value);
  console.log("Total time: ", Date.now() - start, "ms");
});

Deferred.prototype. promise

promise对象可用于注册promise最终解析时要调用的回调。


Deferred.prototype. resolve (result, isError)

Resolve the promise.

Parameters

Object result

the result or error value

Boolean isError

if true the promise is resolved as failed


Promise

一个promise对象。 这个类不被导出,创建一个 deferred对象 来创建一个promise.


Promise.prototype. then (callback, errback)

注册回调函数和errback函数,在解析promise时调用。

Parameters

Function callback

called if the promise is resolved as fulfilled

Function errback

called if the promise is resolved as failed

Returns

Object

a new promise that resolves to the return value of the callback or errback when it is called.


Promise.prototype. wait (timeout)

等待promise被解决。

Parameters

Number timeout

optional time in milliseconds to wait for. If timeout is undefined wait() blocks forever.

Returns

Object

the value if the promise is resolved as fulfilled

Throws

如果promise被解析为失败,请将错误值作为对象

PromiseList (promise...)

PromiseList类允许将几个promise合并为一个。 它表示一个promise,它解析为一个对象数组,每个对象都包含一个值或错误属性,其中包含相应promise参数的值或错误。

PromiseList即使部分或全部部分promise解析为错误,也能成功解析。 处理函数负责检查每个单独的promise结果。

Example

// --- sample output ---
// Done!
// { value: 'i am ok' }
// { value: 1 }
// { error: 'some error' }

let d1 = Deferred(), d2 = Deferred(), d3 = Deferred();

// PromiseList accepts a promise or deferred object
let list = PromiseList(d1.promise, d2, d3);

list.then(function(results) {
  console.log("Done!");
  results.forEach(function(result) {
    console.dir(result);
  });
}, function(error) {
   console.error("Error :-(");
});

d2.resolve(1);
d3.resolve("some error", true);
d1.resolve("i am ok");

Parameters

Promise... promise...

any number of promise arguments.