Meteor with Promises

筅森魡賤 提交于 2019-12-05 18:29:23

(Update: I've logged an issue on github to see if it can be resolved.)

Looks like there's a issue with Meteor.bindEnvironment when used this way.

If it's called from outside a Fiber it won't return it's value. Notice the missing return before Fiber(runWithEnvironment).run()

A simple solution for the moment is to return a Promise instead of the result:

// when passed as a callback to `Promise#then`
//  allows it to resolve asynchronously
var asyncThen = function(fn){
  return function(arg){
    return new Promise(function(resolve, reject){
      fn(arg, resolve, reject);
    })
  };
};

Promise.resolve("asd").then(function(asd){
  console.log("asd is " + asd);
  return "zxc"
}).then(
  asyncThen(
    Meteor.bindEnvironment(function(zxc, resolve, reject){
      console.log("zxc is", zxc);
      resolve("qwe");
    })
  )
).then(function(qwe){
  console.log("qwe is " + qwe);
});

A promise is just a way to write async code in a synchronous fashion. If that's all your after, why not use Meteor.wrapAsync()? In your case, you've got zxc riding cowboy in it's own fiber & who knows when it's coming back. Bluebird is great & super fast on the client, but I think the code is much cleaner using what Meteor gives you:

//*UNTESTED*//
asd = function() { return 'foo';};
asdSync = Meteor.wrapAsync(asd);
asdResult = asdSync();

qwe = function(input) {return input.reverse()};
qweSync = Meteor.wrapAsync(qwe);
qweResult = qweSync(asdResult); //should return 'oof'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!