在我的代碼中,我有一個回傳承諾的異步函式。我知道這個問題之前已經被問過,但是沒有一個解決方案有效。
const fetch = require('node-fetch');
async function getData() {
const response = await fetch(url);
return (await response.json());
}
getData().then( // wait until data fetched is finished
console.log(getData())
)
先感謝您
uj5u.com熱心網友回復:
.then()我認為您只是對回呼的語法有點困惑。
const fetch = require('node-fetch');
async function getData() {
const response = await fetch(url);
return (await response.json());
}
getData().then(data => { // Notice the change here
console.log(data)
// Now within this block, "data" is a completely normal variable
// use it as you wish
})
這個答案與Guerric 的含義相似,但希望以更適合初學者的方式呈現:)
uj5u.com熱心網友回復:
洗掉無用的await,只需將參考console.log作為Promise回呼傳遞:
const fetch = require('node-fetch');
async function getData() {
const response = await fetch(url);
return response.json();
}
getData().then(console.log);
如果您在 中沒有更多控制流getData,則可能根本不需要async/ await:
const fetch = require('node-fetch');
function getData() {
return fetch(url).then(x => x.json());
}
getData().then(console.log);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414259.html
標籤:
上一篇:有人可以澄清F#6中Task和Async之間的用例嗎?
下一篇:函式內部的函式與主體一起運行
