【发布时间】:2018-12-13 14:18:44
【问题描述】:
我正在编写一个小的 JS 脚本,用户在其中输入他的 IBAN,输入前 12 个字符后,我从不同的 URL 请求银行名称和 BIC。因为我必须等待这个请求完成,所以我使我的函数异步并在请求中添加了一个“等待”。但是,我的脚本不再编译并出现以下错误:“解析错误:等待是保留字”指向我新添加的“等待”。由于这个“等待”在几个 if 条件之内,我认为这可能是问题所在。但是,它需要在这些 if 条件之内。那么有没有人知道我做错了什么以及如何在 if 条件中获取 await?
这是我的代码:
function requestBICandBankname(country, bban) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
const url = URL + country.toUpperCase() + '/' + bban;
xhr.open('GET', url, true);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
return resolve(xhr.response);
}
return reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.onerror = function () {
return reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
async function initLookup() {
const ibanData = document.getElementById('iban-details');
let country = '';
let bban;
if (ibanData !== null) {
ibanData.oninput = function (event) {
const iban = ibanData.value;
if (iban.length === 12) {
country = iban.substr(0, 2);
bban = iban.substr(4, 12);
try {
const bankdata = await requestBICandBankname(country, bban);
console.log('bankdata', bankdata);
} catch (err) {
console.log(err);
}
}
};
}
};
export {
initLookup
};
【问题讨论】:
标签: javascript asynchronous async-await