Skip to content

Instantly share code, notes, and snippets.

@hzhangxyz
Last active February 9, 2018 12:48
Show Gist options
  • Save hzhangxyz/86abe08274113153e726766d9f2683ca to your computer and use it in GitHub Desktop.
Save hzhangxyz/86abe08274113153e726766d9f2683ca to your computer and use it in GitHub Desktop.
python和js的async
sleep = (ms)=> new Promise(resolve => setTimeout(resolve, ms))
function bsleep(millis){
var date = new Date()
var curDate = null
do {curDate = new Date()}
while(curDate-date < millis)
}
print = console.log
foo = async (i)=>{
print("开始做点io")
await sleep(1000)
print("嗯,io处理完了")
return i
}
(async()=>{
a = foo(1)
b = foo(2)
c = Promise.all([a,b])
print("假装开始计算")
bsleep(1000)
print("假装就这么算完了")
print("io结果是",await c)
})().then(()=>process.exit())
import asyncio
import time
loop = asyncio.get_event_loop()
async def foo(i):
print("开始io操作")
await asyncio.sleep(1)
print("结束io操作")
return i
async def main():
a = foo(1)
b = foo(2)
c = asyncio.gather(a,b)
print("开始计算点东西")
time.sleep(1)
print("恩,算完了")
print("io结果是",await c)
loop.run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment