MeteorJS:从用户更新中获取成功回调? [英] MeteorJS: Get success callback from user update?

查看:31
本文介绍了MeteorJS:从用户更新中获取成功回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我只想知道我的用户更新在客户端是否成功,以便通知用户更新成功.

So, I just want to know if my user update was successful on client, so I can notify the user that the update worked.

//Client Side
return Meteor.call('handleUpdateUser', _id, _username, function(err, res) {
  if (err) {
    // also, what is best practices for handling these errors?
  }
  console.log(res);
});

//Server Side
Meteor.methods({
  handleUpdateUser(id, username) {
    if (check for user...) {
      return if found
    }
    return Meteor.users.update({_id: id}, {$set: {username: username}}, 
    function(err, count, res) {
      if (err) {
        console.log(err) // again, best practices for handling these errors?
      }
      return res;
    });
 }

我目前在客户端的控制台中获得 undefined.

I currently get undefined in console on client.

permissions.js:

permissions.js:

//Server Side
Meteor.users.allow({
  update:function(userId, doc, fields, modifier) {
    return userId && doc._id === userId;
  }
});

想法?

推荐答案

因为你的服务器端方法是异步的,所以你得到了未定义,如果没有这样对待它,你的客户端将看到同步部分的结果.即在 handleUserUpdate() 结束时返回的隐式 undefined.

you're getting undefined because your server side method is async and, absent treating it as such, your client will see the result of the synchronous part. i.e. the implicit undefined returned at the end of handleUserUpdate().

我使用 Future 将其视为异步.例如

i use a Future to treat it as async. e.g.

const Future = Npm.require('fibers/future');

Meteor.methods({
    handleUpdateUser(id, username) {
        let future = new Future();

        Meteor.users.update({_id: id}, {$set: {username: username}}, function(err, res) {
            if (err) {
                console.log(err);
                future.throw(new Meteor.Error('500', err));
            }

            future.return(res);
        });

        return future.wait();
    }
});

现在,Meteor 将等待通知客户端,直到通过返回或抛出来处理未来.您的客户电话应该能如您所愿.

now, Meteor will wait to notify the client until the future is handled, either through a return or a throw. your client call should work as you expect.

这篇关于MeteorJS:从用户更新中获取成功回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆