Restangular:等待承诺的决心?

omi*_*lke 5 javascript promise angularjs restangular

我是Javascript和AngularJS的新手,这个让我挠头:/

前提

  • REST服务从后端提供我的数据
  • AngularJS 1.2.21和Restangular 1.4.0
  • 一个AngularJS控制器,它要求服务提供所提供的加香版本

是)我有的

这是有问题的方法:

   service.getSlices = function() {

        Restangular.all('entries').getList().then(function(entries) {

            //some rather complex modification of the backend data go here
            //...

            return  resultOfModification; //this is what should be returned for getSlices();
        })

        //I want the resultOfModification to be returned here


    };
Run Code Online (Sandbox Code Playgroud)

这个问题

基本上我想等到getSlices()承诺得到解决resultOfModification才能在实际计算时返回我的承诺.

另外的情况
我也可以想象返回一个承诺getSlices(),然后提供resultOfModification.但是我担心我不太了解这个和/或同时太沮丧/厌倦.

答案和任何建议都是受欢迎的,特别是指向良好的阅读材料.谢谢

t.n*_*ese 10

你不能在那个地方将它作为实际值返回,因为它Restangular是异步的(函数getSlices在你then调用的回调被调用之前被留下).这Promise就是使用的原因.

即使可以Restangular进行同步,也不应该这样做,因为这将阻止浏览器,直到请求数据,这将是一个糟糕的用户体验.

您应该尝试进入Promise设计为看起来像同步代码但行为异步的地方.

您需要在代码中更改的内容是在以下return之前添加Restangular.all:

  service.getSlices = function() {
      return Restangular.all('entries').getList().then(function(entries) {

          //some rather complex modification of the backend data go here
          //...

          return  resultOfModification; //this is what should be returned for getSlices();
      })
  };
Run Code Online (Sandbox Code Playgroud)

这将返回Promise通过.then调用返回的内容.此Promise将解决,resultOfModification因为这是您从其回调中返回的值.

那样你就可以用getSlices 这种方式:

  service.getSlices().then(function(modifiedData) {

  });
Run Code Online (Sandbox Code Playgroud)

承诺可以链接起来:

  (new Promise(function( resolve, reject){
    setTimeout(function() {
      resolve("some");
    },200);
  }))
  .then(function(data) {
    return data+' data';
  })
  .then(function(data) {
    //here a Promise is return which will resovle later (cause of the timeout)
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(data+' !!!!!!');
      },200);
    });
  })
  .then(function(data) {
    //this will have 'some data !!!!!!'
    console.log(data);
  });
Run Code Online (Sandbox Code Playgroud)

哪个会像你那样写的一样:

  var promiseA = new Promise(function( resolve, reject){
    setTimeout(function() {
      resolve("some");
    },200);
  });

  var promiseB = promiseA.then(function(data) {
    return data+' data';
  })


  var promiseC = promiseB.then(function(data) {
    //here a Promise is return which will resovle later (cause of the timeout)
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(data+' !!!!!!');
      },200);
    });
  });

  var promiseD = promiseC.then(function(data) {
    //this will have 'some data !!!!!!'
    console.log(data);
  });
Run Code Online (Sandbox Code Playgroud)