我对JavaScript我相对较新,并且无法找到一种方法来使我的代码等待一些结果,然后才能执行下一步。我对回调进行了一些研究,但我似乎无法与我的代码一起使用。
我正在使用烧瓶框架来开发网页。以下代码调用端点之一要获得JSON响应(name
是我发送到端点的参数,data
是我回来的JSON响应(:
$.getJSON('/if_name_exists', {
name: "sample_name",
}, function(data) {
if (data.check == "True") {
alert("Name already exists! Please enter another name.");
return false;
}
});
问题在于JavaScript不等待此响应并执行我程序中的下一步。这就是我尝试的 -
$.getJSON('/if_name_exists', {
name: "sample_name",
}, function(data) {
if (data.check == "True") {
alert("Name already exists! Please enter another name.");
return false;
}
});
(async () => { await wait(2000); console.warn('done') })();
但是我的代码仍然不等待响应并执行下一步。我如何解决此问题?
简短答案
带有承诺或回调。
看起来您正在尝试制作异步函数,该功能正在等待您的Ajax请求中的响应/错误。
有关工作示例,请参见下文,定义了2个函数,一个是使请求" makerequest"的函数,这返回了诺言,当您的网络请求成功或失败时,它可以解决。
。第二个函数是调用发出请求的函数的函数,在这里您将看到我放置了一个尝试/捕获示例。
这看起来是您所追求的。
const makeRequest = async () => {
return new Promise((resolve, reject) => {
$.getJSON('/if_name_exists', {
name: "sample_name",
}, function(data) {
if (data.check == "True") {
alert("Name already exists! Please enter another name.");
return resolve(false);
}
return resolve(true);
}, reject);
})
};
const runRequest = async () => {
try {
const result = await makeRequest();
// This will not log until your request has succeeded.
console.log(`Result = ${result}`);
} catch (e) {
console.log("Error making request", e);
}
}
// Run the request
runRequest();
听起来您应该查找承诺,回调和异步控制流程,这是值得阅读的!
您可以使用Promise API编写无异步/等待的RunRequest。例如
const runRequest = () => {
makeRequest()
.then((result) => {
console.log(`Result = ${result}`);
})
.catch((error) => {
console.log("Error making request", e);
});
}
或最后,您可以使用回调编写。
const makeRequest = (success, error) => {
$.getJSON(
"/if_name_exists",
{
name: "sample_name"
},
success,
error
);
};
const runRequest = () => {
makeRequest(
data => {
if (data.check == "True") {
alert("Name already exists! Please enter another name.");
return resolve(false);
}
},
error => {
console.log("Error making request", e);
}
);
};
// Run the request
runRequest();
注意:如果$ .getjson返回承诺,那么您可以省略承诺构造函数,不确定是否这样做,即仅支持回调,所以我已经明确返回了MakereQuest的Promise。