如何从客户端的Meteor.call()中分配外部值?

时间:2018-04-19 01:16:36

标签: javascript asynchronous meteor

我遇到this question中所述的类似情况。已经定义了一个服务器Meteor方法,该方法接收一个调用第三方库以获取交换结果的对象。在客户端调用Meteor.call时,我需要将结果值分配给外部变量。但是,我正在以我正在做的方式未定义(我猜它是因为该方法的异步行为)我如何改进以下代码?

//Method on the client side (React.JS Component)
callRatesConvert(fromCurrency, toCurrency, amount) {
    const call = this.props.call;
    let resCall = 0; // Outer variable
    let settings = {};
    settings.fromCurrency = fromCurrency;
    settings.toCurrency = toCurrency;
    settings.amount = amount;
    settings.accuracy = 10;

//Calls Backend method API that returns res successfully
    call('rates.convert', settings, (err, res) => {
        if (err) {
           //Shows UI Error to user
        } else if (res) { //res value is fetched from backend method properly
            resCall = res; // this is not being assigning properly
        }
    });
    console.log('resCall', resCall); //this prints 'undefined'
    return resCall;
    }

2 个答案:

答案 0 :(得分:2)

callRatesConvert转换为返回Promise的函数。如果需要,您还可以使用速记属性赋值来减少代码的语法噪音:

callRatesConvert(fromCurrency, toCurrency, amount) {
  const call = this.props.call;
  const settings = {
    fromCurrency,
    toCurrency ,
    amount,
    accuracy: 10,
  };
  return new Promise((resolve, reject) => {
    call('rates.convert', settings, (err, res) => {
      if (err) {
        //Show Error UI to user
        reject(err);
      } else if (res) {
        resolve(res);
      }
    });
  });
}

然后用

消耗它
someInstantiation.callRatesConvert(...)
  .then((resCall) => {
    // do something with the response
  });

答案 1 :(得分:2)

你有问题,而不是在通话中,它在你的代码上,我会添加一些注释。

Session

所以一个解决方案可能是使用来自meteor的//Method on the client side (React.JS Component) callRatesConvert(fromCurrency, toCurrency, amount) { const call = this.props.call; let resCall = 0; // Outer variable let settings = {}; settings.fromCurrency = fromCurrency; settings.toCurrency = toCurrency; settings.amount = amount; settings.accuracy = 10; //Calls Backend method API that returns res succesfully call('rates.convert', settings, (err, res) => { if (err) { //Show Error UI to user } else if (res) { resCall = res; console.log('resCall', resCall); Session.set("resCall", resCall) } }); }

edit

希望它有所帮助。