【发布时间】:2018-01-17 10:27:16
【问题描述】:
我有一些第三方库,我正在监听它的事件。我有机会修改该库将在 UI 中附加的数据。在数据修改同步之前一切都很好。一旦我涉及 Ajax 回调/承诺,这将无法正常工作。让我举个例子来说明问题。
以下是我收听事件的方式:-
d.on('gotResults', function (data) {
// If alter data directly it works fine.
data.title = 'newTitle';
// Above code alters the text correctly.
//I want some properties to be grabbed from elsewhere so I make an Ajax call.
$.ajax('http://someurl...', {data.id}, function (res) {
data.someProperty = res.thatProperty;
});
// Above code doesn't wait for ajax call to complete, it just go away and
renders page without data change.
// Yes I tried promises but doesn't help
return fetch('http://someurl...').then(function (data) {
data.someProperty = res.thatProperty;
return true;
});
// Above code also triggers the url and gets away. Doesn't wait for then to complete.
});
我无法更改/更改第三方库。我所要做的就是监听事件并更改数据。
任何更好的解决方案。没有。我不能使用异步/等待生成器,因为我希望 ES5 浏览器支持它。
【问题讨论】:
-
那么,您的第 3 方库需要同步响应,但您只有异步响应?那你就吃饱了。
-
我们在谈论哪个库?是否可以不使用内置的结果转换逻辑并用您自己的处理异步的代码包装整个事情?
标签: javascript ajax promise ecmascript-5