我想在實作另一個邏輯之前等待一個承諾。例如,我有一個請求(第一個)和第二個請求(第二個)。當我將提出第二個請求時,在其中我想等待第一個請求,然后添加額外的邏輯。為此,我創建了:
async function resolveAfter2Seconds() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then( json => {
console.log('first');
})
}
async function f1() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(async json => {
await resolveAfter2Seconds();
console.log('second');
})
}
const click = () => {
f1();
}
return (
<div className="App">
<button onClick={click}>click</button>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
因此,當我單擊按鈕時,我想在控制臺中首先看到文本,然后再first看到second。這就是我實作這個的原因:
await resolveAfter2Seconds();
console.log('second');
問題是代碼按以下順序運行:second和first. 如何使第一個請求首先發生?
uj5u.com熱心網友回復:
那是因為您的第一個函式會立即決議。你所擁有的是
async function resolveAfter2Seconds() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json()) // happens later, when the call is completed
.then( json => {
console.log('first');
})
return; // happens now
}
只需添加一個 return 陳述句,事情就會以正確的順序發生
async function resolveAfter2Seconds() {
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then( // etc.
}
(順便說一句,如果您已經在使用async函式,最好去掉thens 并將它們轉換為await語法)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489625.html
標籤:javascript 反应
