我正在使用 Promise 函数来 Promisify XHR,我想知道如何获取响应,如果响应成功,则将其发布回服务器。
我正在做这样的事情
function createChannel(method, url) {
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));
console.log(hashValue);
}
else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send(json);
});
}
createChannel(method, url)
.then(function (datums) {
console.log(datums)
}).catch(function (err) {
console.error('Sorry There Was An Error!', err.statusText);
});
如果此createChannel成功,我将获取哈希值变量,并向服务器发出请求以获取新值。
.then(function (createChannel) {
console.log(createChannel);
});
使用 Promise 可以实现这一点吗? 谢谢你的建议。
最佳答案
在您的 .then()
处理程序中,您只需发出一个新请求并返回该 promise ,将其链接到第一个:
createChannel(method, url).then(function (datums) {
console.log(datums);
// call some other async function here that returns a promise
return someOtherFunctionThatReturnsAPromise(datums);
}).then(function(finalResult) {
console.log(finalResult);
}).catch(function (err) {
console.error('Sorry There Was An Error!', err.statusText);
})
关于javascript - 使用 Promise 构造函数将值发送回服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46822786/