gpt4 book ai didi

jQuery 延迟的优点?

转载 作者:行者123 更新时间:2023-12-03 22:26:41 25 4
gpt4 key购买 nike

 $.ajax("example.php").done(function ()
{
alert(...);
}).fail(function ()
{
alert(...);
}).always(function ()
{
alert(...);
});

对比

  $.ajax("example.php",

success: function ()
{
alert('');
},
error: function ()
{
alert('');
},
complete: function ()
{
alert('');
}
);

抱歉,我看不到有什么优势

能解释一下吗?

或者也许你可以给我举个例子,前者无法通过后者完成......?

最佳答案

对于初学者来说,第二个代码块在语法上甚至无效。我认为这是第一个 :P

的优点<小时/>

但严肃地说:

这只是实现相同最终结果的不同语法。一个直接的好处是,您可以使用延迟为每个结果连接多个函数:

$.get("example.php").done(function ()
{
alert("success 1");
}).done(function ()
{
alert("success 2");
});

否则你必须这样做:

function done1()
{
alert('success 1');
}
function done2()
{
alert('success 2');
}

$.ajax('example.php',
{
success: function ()
{
done1.apply(this, arguments);
done2.apply(this, arguments);
}
});
<小时/>

其他优点,引自How can jQuery deferred be used?

  • Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.
  • ...Fetching data from multiple sources. In the example below, I'm fetching multiple, independent JSON schema objects used in an existing application for validation between a client and a REST server. In this case, I don't want the browser-side application to start loading data before it has all the schemas loaded. $.when.apply().then() is perfect for this.
  • A deferred can be used in place of a mutex. This is essentially the same as the multiple ajax usage scenarios.

关于jQuery 延迟的优点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8030225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com