3 回答
TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
要await真正等到fetch完成,您應(yīng)該返回承諾:
async function firstFunction(){
return fetch("api/favstop/")
.then(response => {
return response.json();
})
.then(data => {
for(var i = 0; i<= data.length; i++){
favouriteStops.push(data[i].stopid)
}
})
};
TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
await您可以通過使用inside firstFunctionlike輕松解決此問題:
async function firstFunction() {
const response = await fetch("api/favstop/")
const data = await response.json();
for (var i = 0; i <= data.length; i++) {
favouriteStops.push(data[i].stopid)
}
};
或者,只返回如下承諾:
async function firstFunction() {
return fetch("api/favstop/")
.then(response => {
return response.json();
})
.then(data => {
for (var i = 0; i <= data.length; i++) {
favouriteStops.push(data[i].stopid)
}
})
};
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
您不需要在異步函數(shù)中使用承諾鏈。事實(shí)上,它有點(diǎn)違背了整個(gè)目的。所以,你的異步函數(shù)看起來有點(diǎn)像這樣:
async function firstFunction(){
const fetcher = await fetch("api/favstop/");
const data = await fetcher.json();
for(var i = 0; i<= data.length; i++){
favouriteStops.push(data[i].stopid)
}
};
添加回答
舉報(bào)
