您的位置:首页 > 移动开发

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

2017-03-08 10:22 471 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: