![](/img/trans.png)
[英]I have been trying to fetch an API and I keep getting : SyntaxError: Unexpected end of JSON
[英]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 Functions和Promises的文檔。
在這種情況下,您可以做一些事情
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
。
如果有error
或reject
被調用, 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.