[英]Why doesn't 'await' wait?
我是Java中的await / async函數的新手。 我寫了以下函數:
getGoogleResults = async () => {
const googleResultUrl = 'http://www.google.com/search?q=bakery&num=60');
// get only Divs within results that have class of 's'
$.getJSON(googleResultUrl, (data) => {
const results = $(data.contents).find('div[class="g"]');
const divs = results.find('div[class="s"]');
console.log(data.contents); // data logged here looks fine in console
return data.contents;
});
}
此功能運行良好,我可以注銷對控制台的響應並查看已解析的數據(排名前60的Google結果)。
但是,我不明白的是,當我調用該函數時,我希望它能等到返回promise后再繼續。 但是,事實並非如此。 當我調用該函數時,該程序無需等待即可立即運行下一行(登錄到控制台的日志):
async startProcess() {
const googleResults = await this.getGoogleResults();
console.log(googleResults); // this gets run immediately, produces 'undefined' in console
}
記錄到控制台的是“未定義”。 因此,很明顯,我做錯了事,但是找不到一個示例來說明可能的情況。 就像程序調用了該函數,但無需等待諾言就立即繼續前進。
編輯:我知道我的函數在此時只是返回data.contents
,而不是解析的Divs。 我現在只是在測試,想在調用異步函數后查看結果。
您需要從函數getGoogleResults
返回Promise對象
getGoogleResults = () => { // You don't need the async keyword here
return new Promise((resolve, reject) => {
const googleResultUrl = 'http://www.google.com/search?q=bakery&num=60');
// get only Divs within results that have class of 's'
$.getJSON(googleResultUrl, (data) => {
const results = $(data.contents).find('div[class="g"]');
const divs = results.find('div[class="s"]');
console.log(data.contents); // data logged here looks fine in console
resolve(data.contents); // Use the function resolve.
});
// Use the function reject for any errors.
});
}
您應該為異步函數返回一個Promise,使其實際上可以等待。 像這樣:
getGoogleResults = async () => {
return new Promise((resolve, reject) => {
const googleResultUrl = 'http://www.google.com/search?q=bakery&num=60');
// get only Divs within results that have class of 's'
$.getJSON(googleResultUrl, (data) => {
const results = $(data.contents).find('div[class="g"]');
const divs = results.find('div[class="s"]');
console.log(data.contents); // data logged here looks fine in console
resolve(data.contents);
}); //TODO call reject() on error
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.