Javascript 需要明确异步函数
我正在尝试从setTimeout获取值。但控制台没有结果。如何处理此Javascript 需要明确异步函数,javascript,ecmascript-6,Javascript,Ecmascript 6,我正在尝试从setTimeout获取值。但控制台没有结果。如何处理此async函数?有谁能帮助我正确理解这一点吗 以下是我的尝试: async function getTheme() { const value = 'abc' setTimeout(() => { return value; }, 3000); } getTheme().then(time => console.log(time)); //getting no result.
async
函数?有谁能帮助我正确理解这一点吗
以下是我的尝试:
async function getTheme() {
const value = 'abc'
setTimeout(() => {
return value;
}, 3000);
}
getTheme().then(time => console.log(time)); //getting no result.
这是因为您返回的是
setTimeout
回调,实际上并没有解决承诺
你想要的是回报一个承诺:
function getTheme() {
const value = 'abc'
return new Promise(resolve => {
setTimeout(() => resolve(value), 3000);
})
}
无需使用async
,因为您已经在getTheme()
函数中返回了承诺
当然,您可以将整个“等待”逻辑抽象为另一个函数:然后,如果您愿意,您可以保持异步:
function sleep(duration) {
return new Promise(resolve => setTimeout(resolve, duration));
}
async function getTheme() {
const value = 'abc';
await sleep(3000);
return value;
}
这是因为您返回的是setTimeout
回调,实际上并没有解决承诺
你想要的是回报一个承诺:
function getTheme() {
const value = 'abc'
return new Promise(resolve => {
setTimeout(() => resolve(value), 3000);
})
}
无需使用async
,因为您已经在getTheme()
函数中返回了承诺
当然,您可以将整个“等待”逻辑抽象为另一个函数:然后,如果您愿意,您可以保持异步:
function sleep(duration) {
return new Promise(resolve => setTimeout(resolve, duration));
}
async function getTheme() {
const value = 'abc';
await sleep(3000);
return value;
}
当promise处于挂起状态时,是否可以阻止整个代码并使其线性化?e、 g:console.log(getTheme();//阻塞3秒console.log('3秒之后');
(我的意思是不在承诺链中,只使用内联代码),然后您需要使用await getTheme();
。如果您需要访问解析的数据,那么const response=await getTheme();
我们不需要(但它是),所以您需要在/yet/other async.yep中这样做,但我不明白为什么await
没有在主线程中实现。问题是什么。当promise处于挂起状态时,是否可以阻止整个代码并使其线性化?例如:console.log(getTheme();//阻止3秒console.log('3秒之后');
(我的意思是不是在承诺链中,只是内联代码)然后你需要使用await getTheme();
。如果你需要访问解析的数据,那么const response=await getTheme();
我们没有(但它是),所以您需要在/yet/other async.yes中执行此操作,但我不理解为什么wait
没有在主线程中实现。问题是什么。