Javascript 使用promise调用Ajax而不复制代码
这可能吗?我想写一个ajax函数,我不想重复它。将不同的参数传递给不同的文件。然后用承诺把它们变成一个对象。我可能会使用扩展运算符。这可能吗Javascript 使用promise调用Ajax而不复制代码,javascript,ajax,es6-promise,Javascript,Ajax,Es6 Promise,这可能吗?我想写一个ajax函数,我不想重复它。将不同的参数传递给不同的文件。然后用承诺把它们变成一个对象。我可能会使用扩展运算符。这可能吗 var myFuncCalls = 0; let promiseAjax = new Promise (function ( resolve,reject) { //possibly use a for look to grab the number of times the loadDoc was called then call the same
var myFuncCalls = 0;
let promiseAjax = new Promise (function ( resolve,reject) {
//possibly use a for look to grab the number of times the loadDoc was called then call the same function and send it to may be an array?
function loadDoc(location) {
myFuncCalls++;
console.log("loadDoc was called :" + myFuncCalls);
var xyz = new XMLHttpRequest();
xyz.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
//console.log(this.responseText)
resolve(this.responseText);
}
};
xyz.open("GET", location, true);
xyz.send();
}
loadDoc("/_js/someitems.json");
loadDoc("/_js/someMoreItems.json");
})
// then grab all that stuff and make one single object using spread operators
promiseAjax.then(function (fromResolve){
// JSON.parse(fromResolve);
var newObj = JSON.parse(fromResolve);
console.log(newObj);
})
我认为最简单的事情是定义异步函数,它返回承诺,并且可以轻松地传递和重用 您可以执行以下操作:
async function loadFile(file) {
...
return {...fileJSON};
}
async function loadFiles() {
const file1JSON = await loadFile('file1');
const file2JSON = await loadFile('file2');
return {...file1JSON, ...file2JSON};
}
loadFiles().then((combinedJSON) => {
...
})
这些函数可以接受参数,并且可以像任何其他函数一样重用。我认为最简单的事情是定义异步函数,它返回承诺,并且可以轻松地传递和重用 您可以执行以下操作:
async function loadFile(file) {
...
return {...fileJSON};
}
async function loadFiles() {
const file1JSON = await loadFile('file1');
const file2JSON = await loadFile('file2');
return {...file1JSON, ...file2JSON};
}
loadFiles().then((combinedJSON) => {
...
})
这些函数可以像其他函数一样接受参数并重用。是的,您可以将URL、任何参数、甚至AJAX调用的类型(POST、GET等)发送到该方法,然后使用它来构建调用。通过这种方式,您可以通过一个“简单”的方法调用,重用相同的方法从客户机执行任何需要执行的操作 此答案中的所有代码均从以下链接复制 您甚至可以通过回调方法发送它。我还向它发送了一个用于处理错误的方法
function makeAjaxCall(url, methodType, callback)
{
$.ajax(
{
url : url,
method : methodType,
dataType : "json",
success : callback,
error : function (reason, xhr){
console.log("error in processing your request", reason);
}
});
}
// git hub url to get btford details
var URL = "https://api.github.com/users/btford";
makeAjaxCall(URL, "GET", function(respJson)
{
document.getElementById("userid").innerHTML = respJson.login;
document.getElementById("name").innerHTML = respJson.name;
document.getElementById("company").innerHTML = respJson.company;
document.getElementById("blog").innerHTML = respJson.blog;
document.getElementById("location").innerHTML = respJson.location;
});
是的,您可以将URL、任何参数、甚至AJAX调用的类型(POST、GET等)发送到该方法,然后使用它构建调用。通过这种方式,您可以通过一个“简单”的方法调用,重用相同的方法从客户机执行任何需要执行的操作 此答案中的所有代码均从以下链接复制 您甚至可以通过回调方法发送它。我还向它发送了一个用于处理错误的方法
function makeAjaxCall(url, methodType, callback)
{
$.ajax(
{
url : url,
method : methodType,
dataType : "json",
success : callback,
error : function (reason, xhr){
console.log("error in processing your request", reason);
}
});
}
// git hub url to get btford details
var URL = "https://api.github.com/users/btford";
makeAjaxCall(URL, "GET", function(respJson)
{
document.getElementById("userid").innerHTML = respJson.login;
document.getElementById("name").innerHTML = respJson.name;
document.getElementById("company").innerHTML = respJson.company;
document.getElementById("blog").innerHTML = respJson.blog;
document.getElementById("location").innerHTML = respJson.location;
});
使用Promise.all()将两个调用结合在一起,这样就可以对解析的数据数组进行任何处理
function loadDoc(location) {
return new Promise (function ( resolve,reject) {
var xyz = new XMLHttpRequest();
xyz.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
}
};
xyz.open("GET", location, true);
xyz.send();
});
}
const urls = ["/_js/someitems.json", "/_js/someMoreItems.json"]
Promise.all(urls.map(url=>loadDoc(url))).then(responses =>
console.log(responses);
)
使用Promise.all()将两个调用结合在一起,这样就可以对解析的数据数组进行任何处理
function loadDoc(location) {
return new Promise (function ( resolve,reject) {
var xyz = new XMLHttpRequest();
xyz.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
}
};
xyz.open("GET", location, true);
xyz.send();
});
}
const urls = ["/_js/someitems.json", "/_js/someMoreItems.json"]
Promise.all(urls.map(url=>loadDoc(url))).then(responses =>
console.log(responses);
)
这种行为可以通过
承诺存档。所有都是白色的异步+等待和使用更多最先进的调用(获取)使代码看起来更干净
async function loadAll(docs) {
return Promise.all(docs.map(async doc => {
const result = await fetch('http://example.com/movies.json');
return result.json();
}));
}
(async function() {
const responses = await loadAll(["/_js/someitems.json", "/_js/someMoreItems.json"]);
console.log(responses);
})();
注意:wait只能从异步函数中使用。
注2:代码未经测试这种行为可以通过承诺存档。所有
white使用异步
+等待
和使用更多最先进的调用(获取
)使代码看起来更干净
async function loadAll(docs) {
return Promise.all(docs.map(async doc => {
const result = await fetch('http://example.com/movies.json');
return result.json();
}));
}
(async function() {
const responses = await loadAll(["/_js/someitems.json", "/_js/someMoreItems.json"]);
console.log(responses);
})();
注意:wait只能从异步函数中使用。
注2:代码未经测试,带有承诺。所有和对象。分配
function loadDoc(location) {
return new Promise((resolve, reject) => {
var xyz = new XMLHttpRequest();
xyz.onreadystatechange = () => {
if (this.readyState == 4 && this.status == 200) {
resolve(JSON.parse(this.responseText));
} else {
// resolving with empty object to avoid breaking other fetch if one failed
resolve({});
}
};
xyz.open("GET", location, true);
xyz.send();
});
}
const loadDocs = (paths) => Promise.all(paths.map(path => loadDoc(path))
.then(results => {
// combine all result into single object
return Object.assign({}, ...results);
}));
// example
loadDocs([
"/_js/someitems.json",
"/_js/someMoreItems.json"
]).then(function(finalCombinedObject) {
// other logic here
});
使用Promise.all
和Object.assign
function loadDoc(location) {
return new Promise((resolve, reject) => {
var xyz = new XMLHttpRequest();
xyz.onreadystatechange = () => {
if (this.readyState == 4 && this.status == 200) {
resolve(JSON.parse(this.responseText));
} else {
// resolving with empty object to avoid breaking other fetch if one failed
resolve({});
}
};
xyz.open("GET", location, true);
xyz.send();
});
}
const loadDocs = (paths) => Promise.all(paths.map(path => loadDoc(path))
.then(results => {
// combine all result into single object
return Object.assign({}, ...results);
}));
// example
loadDocs([
"/_js/someitems.json",
"/_js/someMoreItems.json"
]).then(function(finalCombinedObject) {
// other logic here
});
您需要什么样的向后兼容性?你能改用基于承诺的吗?您好,现在不需要兼容性。我正在努力避免代码重复。。。。但是你提出了一个有趣的观点,我不知道可能存在兼容性问题。Promise.all()
你到底想要我做什么还不清楚。您需要一个可以传递文件名数组的函数,它执行一些异步操作并返回给您。。。到底是什么?你能试着更具体一点吗?我认为值得一提的另一件事是,如果你请求多个JSON文件并在客户端将它们组合在一起,你最大的改进领域可能是服务器,因此客户端可以在一个请求而不是多个请求中接收所有数据。你需要什么样的向后兼容性?你能改用基于承诺的吗?您好,现在不需要兼容性。我正在努力避免代码重复。。。。但是你提出了一个有趣的观点,我不知道可能存在兼容性问题。Promise.all()
你到底想要我做什么还不清楚。您需要一个可以传递文件名数组的函数,它执行一些异步操作并返回给您。。。到底是什么?您能否尝试更具体一点我认为值得一提的另一件事是,如果您请求多个JSON文件并在客户端将它们组合在一起,您最大的改进领域可能是服务器,因此客户端可以在一个请求而不是多个请求中接收所有数据。