#javascript #jquery #ajax #nested
#javascript #jquery #ajax #вложенные
Вопрос:
Я рассмотрел множество решений, в которых используются deffered и promises.Пробовал эти решения в моем сценарии, но не смог найти решение.Я боролся с этим на протяжении всего дня.Мой сценарий таков.
У меня есть множество клиентов.И мне нужно выполнить некоторые определенные действия для каждого клиента по одному, которые определяются как ajax.
private function main()
{
customers=["customer1","customer2"]
customers.forEach(function(customer) {
function1();
function2();
function3();
}
}
private function function1()
{
$.ajax({
type: "POST",
url: Url1,
data: {},
success: function (data) {
console.log("a");
},
dataType: 'JSON'
});
}
private function function2()
{
$.ajax({
type: "POST",
url: Url2,
data: {},
success: function (data) {
console.log("b");
},
dataType: 'JSON'
});
}
private function function3()
{
$.ajax({
type: "POST",
url: Url3,
data: {},
success: function (data) {
console.log("c");
},
dataType: 'JSON'
});
}
Когда вызывается основная функция .Мой желаемый результат
a
b
c
a
b
c
Но результат, который я получаю, таков
a
a
b
b
c
c
Пожалуйста, помогите мне найти решение.
Ответ №1:
Вызов Ajax по умолчанию является асинхронным. Экшен.
function send() {
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'a'
}
).then(
() => {
console.log('a is sended');
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'b'
}
).then(
() => {
console.log('b is sended');
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'c'
}
).then( () => console.log('c is sended') )
}
)
}
)
}
Комментарии:
1. ДА. Я это знаю. Я не хочу, чтобы он делал async:false, поскольку он устарел. Я ищу другие решения, используя отложенный или обещанный.
2. Я пробовал это .. похоже на вывод, который я получаю, как указано в моем вопросе
Ответ №2:
Наконец, я решил свою проблему, выполнив рекурсивный вызов функции без использования цикла.
var customers=["customer1","customer2"];
var currentIndex=0;
private function main()
{
if(customers[currentIndex]){
function1().done(function(data) {
console.log("a");
function2().done(function(data) {
console.log("b");
function3().done(function(data) {
console.log("c");
currentIndex ;
main();
});
});
});
}
}
private function1()
{
return $.ajax({
type: "POST",
url: url1,
data: {},
dataType: 'JSON'
});
}
private function2()
{
return $.ajax({
type: "POST",
url: url2,
data: {},
dataType: 'JSON'
});
}
private function3()
{
return $.ajax({
type: "POST",
url: url3,
data: {},
dataType: 'JSON'
});
}
И текущий выходной сигнал равен
a
b
c
a
b
c