Я разрабатываю хром расширение, в котором при нажатии кнопки мне нужны данные из ajax ПОЛУЧИТЬ, а после этого нужно перейти к дальнейшей обработке. Для этого я хочу синхронный вызов ajax, но он дает мне ошибку
Error: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects on the end user's experience.
Я знаю, что эта ошибка связана с тем, что я установил асинхронный = ложь, но до тех пор, пока я не получу данные из API, я не могу перейти к дальнейшей обработке. Ниже мой код:
var nonce;
window.addEventListener('load', function load(event){
var createButton = document.getElementById('send');
createButton.addEventListener('click', function() {
signTransaction('abc',12,'abc');
});
});
function signTransaction(to,amount,inputhex){
nonce = getNonce();
console.info(nonce);
tx = {
To : to,
PrivateKey : pri,
Balance : amount,
Nonce : String(nonce),
Gas : "1",
Type : "a64",
Input : inputhex
}
let transaction = new sdag.Signs.NewTransaction(pri,tx);
}
function getNonce() {
var request = new XMLHttpRequest();
request.open('GET', 'http://192.168.xx.xx:9999/getAccount?address=xxxxxxxxx', false);
request.onload = function () {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
nonce = data.Nonce;
} else {
console.info('error');
}
}
// Send request
request.send(null);
return nonce;
}
Вы можете проверить код. В signTransaction() сначала мне нужен одноразовый номер из getNonce() функции, а затем можно идти дальше. Итак, я установил для этой функции значение async false.
Может ли кто-нибудь помочь мне с этим?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


За МДН:
Do not use synchronous requests outside Web Workers.
Вы можете настроить логику между двумя функциями таким образом, чтобы вы определили signTransaction() для получения вывода вашего XML-запроса, а затем вложили signTransaction в getNonce. В этом смысле getNonce становится контроллером, а signTransaction — промежуточным выходом обратно в getNonce.
function signTransaction(to,amount,inputhex, nonceResponse){
let tx = {
To : to,
PrivateKey : pri,
Balance : amount,
Nonce : String(nonce),
Gas : "1",
Type : "a64",
Input : inputhex
}
let transaction = new sdag.Signs.NewTransaction(pri,tx);
return transaction
}
function getNonce(to,amount,inputhex) {
var request = new XMLHttpRequest();
request.open('GET', 'http://192.168.51.212:9999/getAccount?
address=23471aa344372e9c798996aaf7a6159c1d8e3eac', true);
//third arg to request.open() could be omitted if intent is to process call asynchronously
request.onload = function () {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
nonce = data.Nonce;
return signTransaction(to,amount,inputhex,data)
} else {
console.info('error');
}
}
Вы также можете использовать асинхронный/ожидающий синтаксис ES6, чтобы воспользоваться промисами и выдать поток программы во время выполнения асинхронных операций:
async function signTransaction(to,amount,inputhex){
nonce = await getNonce(); // `await` call yields flow back to the thread while the other async function getNonce() is executed
tx = {
To : to,
PrivateKey : pri,
Balance : amount,
Nonce : String(nonce),
Gas : "1",
Type : "a64",
Input : inputhex
}
let transaction = new sdag.Signs.NewTransaction(pri,tx);
}
async function getNonce() {
var request = new XMLHttpRequest();
request.open('GET', 'http://192.168.51.212:9999/getAccount?address=23471aa344372e9c798996aaf7a6159c1d8e3eac', true);
//third arg to request.open() could be omitted if intent is to process call asynchronously
request.onload = function () {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
nonce = data.Nonce;
return nonce; // returning here resolves the promise that is implicitly returned from an async function with the value returned from your XML call. This value triggers continuation of the signTransaction function with XML call result
} else {
console.info('error');
}
}
// Send request
request.send(null);
}
Я думаю, вы забыли изменить async false в функции getNonce().