Javascript 具有同步和异步代码的异步函数
我有一个返回true或false的异步函数。它看起来像下面的一个:Javascript 具有同步和异步代码的异步函数,javascript,async-await,Javascript,Async Await,我有一个返回true或false的异步函数。它看起来像下面的一个: class User { async canManageGroup(group) { if (typeof group === 'number') { // group - id group = await getGroupById(group) } // else group is already loaded from DB return this.id === grou
class User {
async canManageGroup(group) {
if (typeof group === 'number') {
// group - id
group = await getGroupById(group)
} // else group is already loaded from DB
return this.id === group.manager.id
}
}
如果group
参数是组的ID,则函数将对DB进行异步调用,因此函数canManageGroup
将异步执行。但如果group
参数是group model,那么函数将只调用返回this.id==group.manager.id
,或者同步执行。以这种方式编写代码是一种好的做法吗?或者我应该将同步代码转换为异步代码
function makeAsync(cb) {
return new Promise(resolve => setImmediate(() => resolve(cb())))
}
class User {
async canManageGroup(group) {
if (typeof group === 'number') {
// group - id
group = await getGroupById(group)
} // else group is already loaded from DB
return await makeAsync(() => this.id === group.manager.id)
}
}
第一个是正确的。如果不需要异步,则无需强制任何东西。上下文切换不是免费的,因此如果不需要等待任何事情完成,就不要尝试进行切换。您可以毫无问题地使用第一个示例 使用
async
时,函数将返回一个Promise
。如果您的代码是sync
,则返回的承诺的状态将是已解析
,并且在其上运行任何与承诺相关的代码是安全的(然后
,捕获
,等等)
例如:
异步函数truePromise(){
返回true;
}
truePromise().then(函数(值){
日志(“承诺值:”,值);
});代码>基于您对其中一个答案的评论,您关心的是该问题的答案 问题是,这个函数是不一致的:有时是异步的,有时不是。假设您有这样一个消费者: 在像nodejs这样的js环境中,通常的做法是,可以异步执行的回调应该始终被称为异步,不管实际代码是否真的是异步的 因此,您想知道下面的代码是否会打破这种惯例
async function doSomething() {
return true
}
doSomething()
.then(res => {
console.log(res)
})
事实并非如此,因为这里您处理的是承诺,并且允许立即解决承诺,上面的代码基本上与您编写的代码相同:
Promise.resolve(true)
.then(res => {
console.log(res)
})
异步行为在链接部分(then
/catch
)中得到保证,传递给then
/catch
的回调将被称为异步:
异步函数doSomething(){
返回真值
}
console.log('before');
doSomething()
。然后(res=>{
log('with in callback')
})
console.log('after')代码>不,不要做第二个。。。这在
async
函数中是多余的。我知道这段代码可以工作。但在异步函数中编写同步代码好吗?根据这篇文章,我不应该在异步函数中编写同步代码。太长,读不下去了如果您使用async
关键字,就可以了。如果不这样做,可能会出现不一致性问题。顺便说一句,当您使用async
关键字时,链接答案的作者指出的一致性问题不是问题。