我刚刚开始在javascript中使用promise函数,我确实喜欢它,但我遇到了一个问题。
我从promise对象获取一个值,然后在异步promise函数中将响应发送回服务器。当我将值发送回服务器,并尝试查看值是什么时,它返回undefined。
var xhr = new XMLHttpRequest();
function createFirstChannel(method, rippleApi) {
return new Promise(function (resolve, reject) {
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.readyState == 4 ) {
var hashValue = resolve(JSON.parse(xhr.responseText));
}
else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send(json);
});
}
从我在下一个promise函数中使用的第一个函数返回一个值
async function createChannel(method, url) {
var datums = await createFirstChannel(method, url);
//method to return hash value from json request
for (var key in datums) {
var tx_json = datums[key]['json'];
datums = (json['hash']);
console.log(datums);
}
//creating the json request to send back out again using POST METHOD
var channel= {
"method": "tx",
"par": [{
"transaction": datums
}]
}
var jsonPayee = JSON.stringify(channel);
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.readyState == 4) {
users = JSON.parse(xhr.responseText);
}
};
xhr.send(jsonPayee);
return users;
}
createChannel(method, url).then(datums => {
console.log(datums);
}).catch(function (err) {
console.error('Sorry There Was An Error!', err.statusText);
});
i get "undefined" response at console.log. is there any way to resolve this error? Thanks for the help