Javascript 在JS中使用异步而不等待是否可能?
我正在尝试一个小实验,在这里使用异步而不等待。因此,我在这里所做的是在fetchapi中使用Async和promise。我没有在Javascript 在JS中使用异步而不等待是否可能?,javascript,Javascript,我正在尝试一个小实验,在这里使用异步而不等待。因此,我在这里所做的是在fetchapi中使用Async和promise。我没有在第14行中获得回报,但是第8行工作正常。附件是代码。应该是什么?非常感谢,请提前 async function getUserAsync(name) { let data fetch(`https://api.github.com/users/${name}`) .then(response => response.json()) .then(r
第14行
中获得回报,但是第8行
工作正常。附件是代码。应该是什么?非常感谢,请提前
async function getUserAsync(name)
{
let data
fetch(`https://api.github.com/users/${name}`)
.then(response => response.json())
.then(response => {
data = response
console.log(data) //line 8
})
return data
}
getUserAsync('john')
.then(data => console.log(data)) //line 14
您可以返回
fetch()
,然后获得Promise对象
异步函数getUserAsync(名称){
回传(`https://api.github.com/users/${name}`)
.then(response=>response.json())
}
getUserAsync('john')
。然后(data=>console.log(data))或者您可以从异步函数创建并返回自定义承诺:
async function getUserAsync(name)
{
return new Promise((resolve, reject) => {
let data
fetch(`https://api.github.com/users/${name}`)
.then(response => response.json())
.then(response => {
data = response
console.log(data) //line 8
resolve(data)
})
.catch(error => reject(error))
})
}
getUserAsync('john')
.then(data => console.log(data)) //line 14
您的意思是将
fetch
分配给data
?回答您的问题:可以,但您需要确保函数返回承诺。否则,它返回的任何内容都将被包装在一个立即解析的文件中。有时候这不是你想要的;当然,在你的特殊情况下是不行的。