nodejs 异步转同步整理

主要是集中参考使用方法,可以结合自己的场景解决问题

参考代码

const co =require("co")
const AsyncUtil = require('async-utility').default;
async function demo(){
    return {
        name:"dalong",
        age:33
    }
}
var result =co(function* () {
    var result = yield demo();
    console.log("co result:",result)
    return result;
  })
 
 
let myresult = AsyncUtil.resolvePromise(result)
 
console.log("AsyncUtil",myresult)
 
 
function* demoapp(){
    yield demo();
    yield demo();
}
 
let appdemo = demoapp().next()
 
appdemo.value.then(data=>{
    console.log(data)
})
 
let myresult2 = AsyncUtil.resolvePromise(appdemo.value)
 
console.log("generate",myresult2);
 
(async ()=>{
    let info =await demoapp().next().value
    console.log("await info",info)
})()

说明

以上包含了async/await 以及generator,co,async-utility(依赖deasync),同时推荐还是别使用deasync,以下有参考连接

参考资料

https://joecreager.com/5-reasons-to-avoid-deasync-for-node-js/
https://github.com/tj/co

posted on 2021-04-26 00:10  荣锋亮  阅读(39)  评论(0编辑  收藏  举报

导航