簡體   English   中英

我一直在嘗試從 XMLRPC 客戶端獲取數據

[英]I have been trying to fetch data from XMLRPC client

這是我寫的一段代碼。 我無法從 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);
      }
    });
  }
  );
}

我建議您閱讀有關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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM