我有一個這樣定義的簡單 JS 函式:
function firstFunction() {
$.ajax({
url: "/path/to/my/endpoint",
type: "GET"
}).done(function (data) {
localStorage.setItem("myItem", data);
});
}
稍后,我定義了另一個函式,如下所示:
function mySecondFunction() {
if(localStorage.getItem("myItem") == null) {
// Here I want to call firstFunction() and stop everything until it finishes
}
//Immediately use localStorage.getItem("myItem") for other purposes
//no matter I entered the if() or not
}
使用簡單async: false
的 in $.ajax
,它可以作業,但我已經看到它將被棄用,我想避免這種解決方案。
您能否建議mySecondFunction
進入 my 時如何等待if()
?
我試過$.when()
但沒有成功,也許我做錯了什么?
我嘗試了類似的東西
function mySecondFunction() {
var deferred = $.Deferred();
if(localStorage.getItem("myItem") == null) {
$.when(firstFunction()).then(function () {
deferred.resolve();
})
}
else {
deferred.resolve();
}
//other instructions
}
但是other instructions
在結束之前被稱為firstFunction()
uj5u.com熱心網友回復:
做出firstFunction()
回報承諾。
function firstFunction() {
return new Promise((res, err) => {
$.ajax({
url: "/path/to/my/endpoint",
type: "GET"
}).done(function (data) {
localStorage.setItem("myItem", data);
res()
});
});
}
使mySecondFunction
aysnc。
async function mySecondFunction() {
if(localStorage.getItem("myItem") == null) {
await firstFunction();
}
localStorage.getItem("myItem")
...
}
這就是我建議您這樣做的方式,因為 ajax 請求不會阻止其他代碼的執行,例如按鈕回呼。Async/await 和 Promise 一開始很難掌握,所以這里有一些關于它們如何在幕后作業的閱讀。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
uj5u.com熱心網友回復:
只需用回圈更改您的if
子句并在該回圈中while
呼叫您的子句firstFunction
。
例子:
function mySecondFunction() {
while(localStorage.getItem("myItem") == null) {
firstFunction()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/478916.html
標籤:javascript jQuery 异步 承诺 等待