我正在尝试将代码从使用Async / Await方法转换为基本的.then()承诺。原因是Async / Await在IE上不起作用。 我对Promise陌生,并且在使用Async / Await时却一头雾水,但现在需要稍微转换一下时间才能使我的代码在IE中工作。
在Codepen.io上使用Async / Await here运行代码
请,我们将不胜感激。
Javascript尝试不使用Async / Await:
const getPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
$.getJSON( countriesUrl, function( data ) {
}).done(function(data){
resolve(data);
}).fail(function(error){
var reason = new Error('mom is not happy today');
reject(reason);
});
}, 500);
});
};
var bcp = {
init: function(){
bcp.topbar = parseInt($('.topbar').css('height'), 10);
bcp.bottombar = parseInt($('.bottom-bar').css('height'), 10);
if(!bcp.countriesLoaded){
console.log('testing');
bcp.addCountries().then((countries) => {
console.log('hello');
bcp.popup = $($.fancybox.getInstance().current.src)[0];
bcp.distributorArrays(countries);
});
}else {
bcp.addEventListeners();
}
},
toggleCountrySection: function(){
$('#locationModal').find('.loading').toggleClass('show');
$('.content').toggle();
},
getCountries: function() {
console.log('get Countries');
bcp.toggleCountrySection();
},
addCountries: function() {
(() => {
getPromise()
.then(result => {
console.log('result', result);
var data = result;
return data;
}).then(function(data){
var countries = data;
bcp.toggleCountrySection();
bcp.countriesLoaded = true;
console.log('test', countries);
return countries;
})
.catch(err => {
console.log(err);
});
})();
};
我从没收到console.log('hello')。因此,我的函数bcp.addCountries()。then((countries)=> {})无法重新启动,或者我感觉我没有正确使用.then()。
这是我使用Async / Await的工作代码:
init: function(){
bcp.topbar = parseInt($('.topbar').css('height'), 10);
bcp.bottombar = parseInt($('.bottom-bar').css('height'), 10);
if(!bcp.countriesLoaded){
bcp.addCountries().then((countries) => {
bcp.popup = $($.fancybox.getInstance().current.src)[0];
bcp.distributorArrays(countries);
});
}else {
bcp.addEventListeners();
}
},
toggleCountrySection: function(){
$('#locationModal').find('.loading').toggleClass('show');
$('.content').toggle();
},
getCountries: function() {
console.log('get Countries');
bcp.toggleCountrySection();
return new Promise(resolve => {
setTimeout(() => {
$.ajax({
url: countriesUrl,
success: function(data) {
var results = JSON.parse(data);
resolve(results);
}
});
}, 1500);
});
},
addCountries: async function() {
var countries = await bcp.getCountries();
bcp.toggleCountrySection();
bcp.countriesLoaded = true;
return countries;
},
答案 0 :(得分:2)
获取工作版本(来自您的评论Here is my working code using Async/Await:
),然后将addCountries
更改为此版本。
使用的答案:
return bcp.getCountries().then((countries) => {
console.log('test', countries);
bcp.toggleCountrySection();
bcp.countriesLoaded = true;
return countries;
});