【问题标题】:I have been trying to fetch data from XMLRPC client我一直在尝试从 XMLRPC 客户端获取数据
【发布时间】:2021-12-20 02:18:43
【问题描述】:

这是我写的一段代码。我无法从 Promise 访问数据以供以后使用。

function forgotPassword(params) {
  return new Promise(function (resolve, reject) {
    return client.methodCall('forgotPassword', params, function (error, value) {
      if (error === null) {
        if (value === true) {
          console.log('Password Sent!!');
          //subpy.kill('SIGINT');
          return resolve('Password Sent!!');
        }
        else {
          console.log('User Not Found!!');
          //subpy.kill('SIGINT');
          return resolve('User Not Found!!');
        }
      }
      else {
        console.log('Error while doing the Operation!!');
        //subpy.kill('SIGINT');
        return reject(error);
      }
    });
  }
  );
}

【问题讨论】:

  • 这里的数据是什么?
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • @DankDizaster 这里的数据是密码是否发送到相应的邮件ID。我已经向函数返回了一个特定的值。我正在尝试存储 Promise 中的值以供以后使用,但我无法做到。

标签: javascript xml-rpc xmlrpcclient


【解决方案1】:

我建议您阅读Async FunctionsPromises 上的文档。

在这种情况下,您可以做一些事情

new Promise(function (resolve, reject) {
    return client.methodCall('forgotPassword', params, function (error, value) {
      if (error === null) {
        if (value === true) {
          console.log('Password Sent!!');
          //subpy.kill('SIGINT');
          return resolve('Password Sent!!');
        }
        else {
          console.log('User Not Found!!');
          //subpy.kill('SIGINT');
          return resolve('User Not Found!!');
        }
      }
      else {
        console.log('Error while doing the Operation!!');
        //subpy.kill('SIGINT');
        return reject(error);
      }
    });
  })
.then(res => console.log(res))
.catch(rej => console.log(rej));

如果resolve 被调用,then 将被调用。

如果有errorreject 被调用,则catch 将被调用。

另一种方法是在 async 函数中使用 await 等到您从 promise 对象中获得结果

function myPromiseFunction(){
    return new Promise(function (resolve, reject) {.....
}

async function myfunction() {
  try {
      var res = await myPromiseFunction(); // waits until result from promise
      console.log(res);
  } catch (error){
      console.log(error);
  }
  
}

myfunction();

【讨论】:

  • 感谢您的帮助。这对我很有帮助。
猜你喜欢
  • 2019-09-07
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 2019-08-15
  • 2019-02-12
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
相关资源
最近更新 更多