[英]Javascript async function instead of new promise
I just learnt " async " that " async " ensures that the function returns promise then i tried to make a promise with writing " async " instead of writing " new Promise " and it didn't work out so i want to know is it wrong syntax or it will never work out and i will have to write only new promise ?我刚刚学会了“ async ”,“ async ”确保 function 返回 promise 然后我尝试用写“ async ”而不是写“ new Promise ”来制作 promise 但它没有成功所以我想知道它是不是错了语法或它永远不会成功,我将不得不只写新的 promise ?
// This is a code // 这是一段代码
async function gets(){
let gets1 = async()=>{
return 45;
}
gets1.then((value)=>{
console.log(value, "inside gets1")
})
}
gets()
As already pointed out, you need to call a function fn().then(
, not just reference it fn.then(
.正如已经指出的那样,您需要调用function fn().then(
,而不仅仅是引用它fn.then(
。
Also if you don't use the await
, you also don't need the wrapping await
另外,如果你不使用await
,你也不需要包装await
const gets = () => { const gets1 = async() => { return 45; } gets1().then((value) => { console.log(value, "inside gets1") }) }; gets();
Or use async
with await
to get rid of Promise.then()
:或者使用async
with await
来摆脱Promise.then()
:
const gets = async () => { const gets1 = async() => { return 45; }; const value = await gets1(); console.log(value, "inside gets1") }; gets();
Make sure to read top to bottom: async Function确保从上到下阅读: async Function
You forgot to call the function您忘记拨打 function
It should be gets1().then()
and not gets1.then()
它应该是gets1().then()
而不是gets1.then()
async function gets(){ let gets1 = async()=>{ return 45; } gets1().then((value)=>{ console.log(value, "inside gets1") }) } gets()
The whole thing will work without the outer async
function too:整个事情也可以在没有外部async
function 的情况下工作:
let gets1 = async()=>"msg from gets1"; gets1().then(console.log)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.