如何在 RactiveJS 中使用 Promise?

How to use Promises in RactiveJS?

虽然有example in Ractive docs,但我是promises初学者,看不懂上面的例子:

var Promise = Ractive.Promise;

var p = new Promise( function ( fulfil, reject ) {
  doSomethingAsync( function ( error, result ) {
    if ( error ) {
      return reject( error );
    }

    fulfil( result );
  });
});

我如何使用 Ractive 的实现来异步 运行 一些功能?

编辑:一个用例示例是当我在同一个函数中有同步异步操作并且我需要return 处理所有这些操作时的 Promise。

这是一个关于 promises 的问题,而不是关于 Ractive 的问题,所以 this MDN article 值得一读,尽管它有点沉重。

但基本上,如果您想等到几个操作完成,请使用 Promise.all:

var ready = Promise.all([
  getJSON( '/data.json' ), // async (returns a promise)
  domReady(),              // async
  reticulateSplines()      // sync
]);

getJSONdomReady会同时执行。 reticulateSplines 也是如此,因为它是同步的,所以并不重要。 ready 的值现在是一个承诺,它将用一个包含这三个操作结果的数组来实现:

ready.then( function ( values ) {
  var data     = values[0];
  var document = values[1];
  var splines  = values[2];
  // some code happens
}).catch( function ( err ) {
  // if something went wrong with any of those three
  // functions (e.g. couldn't find data.json), we'll
  // end up here
});

如果您使用类似 babel 的方式转译您的代码,您还可以使用解构:

ready.then( ([ data, document, splines ]) => {
  // some code happens
}).catch( err => {
  // handle error
});

另一个有用的函数,如果你正在处理可能同步可能异步的东西(尽管最好避免这种事情)是 Promise.resolve:

function crazyTown () {
  if ( Math.random() < 0.5 ) {
    return 'sync!';
  } else {
    return new Promise( function ( fulfil, reject ) {
      setTimeout( function () {
        fulfil( 'async!' );
      }, 500 );
    });
  }
}

Promise.resolve( crazyTown() ).then( function ( type ) {
  console.log( type );
});

如果您的浏览器本身支持 promises,Ractive 将使用它们(即 Ractive.Promise === window.Promise)——如果不支持,它会使用自己的符合规范的实现。