Simple Sync is a simple sync function-wrapper for node js, based on fibers module.

https://www.npmjs.com/package/simplesync

Simple Sync is a simple sync function-wrapper for node js, based on fibers module.

How to install:

npm install simplesync

How to use:

//First you need to require simplesync module
var sync = require('simplesync');

//Any sync call must be in a sync block.
sync.block(function() {
	//Standard async call
	Some_Async_Function(123, function(ta) {
		//ta will be 123.
	});

	//We name the first parameter of callback to "ta"
	//If there is multi parameters in callback function, just using like this:
	//sync.cb("ta1", "ta2", "ta3");
	//
	var result = sync.wait(Some_Async_Function(123, sync.cb("ta")));

	//Now we can use the "ta" in result. This will print 123.
	//
	console.log("TA:= " + result.ta);

	//And you can wait for multi functions finished, like this:
	result = sync.wait(function() {
		Some_Async_Function(123, sync.cb("ta"));
		Some_Async_Function2(123, sync.cb("ta", "ta2"));
	});

	//
	//result[0].ta  = 123;
	//result[1].ta  = 124;
	//result[1].ta2 = 678;
}

//Sample async function. It is no matter about this function is in or not in the sync block.
function Some_Async_Function(input, callback) {		
	callback(input);
}

function Some_Async_Function2(input, callback) {		
	callback(input + 1, 678);
}

Chinese document: 支持单个函数异步转同步调用,或者一组函数并行运行后转同步调用。

如何使用: //首先引入模块, var sync = require('simplesync');

//任何同步调用都必须位于一个sync.block块内, sync.block描述可以嵌套。
sync.block(function() {
    //标准异步调用方式
    Some_Async_Function(123, function(ta) {
        //这里参数ta的值是124
    });
    //这是同步调用方式, result.ta就是124
    var result = sync.wait(Some_Async_Function(123, sync.cb("ta")));

    //多个参数就这么办
    function Async_Function2(input, callback) {
        callback(input, 456);
    }
    //这里result.ta就是123, result.ta2就是456了
    result = sync.wait(Async_Function2(123, sync.cb("ta", "ta2")));

	//当需要等待多个函数并行运行后统一结束的,用如下的方式:
	result = sync.wait(function() {
		Some_Async_Function(123, sync.cb("ta"));
		Some_Async_Function2(123, sync.cb("ta", "ta2"));
	});

	//
	//result[0].ta  = 123;
	//result[1].ta  = 124;
	//result[1].ta2 = 678;	    
}

//异步调用函数可以在sync.block内,也可以不在,无所谓。
function Some_Async_Function(input, callback) {        
    callback(input+1);
}

function Some_Async_Function2(input, callback) {		
	callback(input + 1, 678);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值