te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - how to create a custom asynchronous function in node.js - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to create a custom asynchronous function in node.js - Stack Overflow

programmeradmin3浏览0评论

Ii'm trying to do something like.

function fun1(){
  for(var j=0;j<20;j++)
  {
    var n = j;
    console.log("i= "+n);
  }
}
function fun2()
{
  console.log("In Callback");
}  

fun1();
fun2();

Ii'm trying to do something like.

function fun1(){
  for(var j=0;j<20;j++)
  {
    var n = j;
    console.log("i= "+n);
  }
}
function fun2()
{
  console.log("In Callback");
}  

fun1();
fun2();

its working fine till now and got output as expected.

But, I want to call function fun1() and fun2() asynchronously it means fun2() call before fun1(), b'coz fun1() will take some time for plete the execution as pare to fun2().

How can I achieve this, Node.js provide asynchronous function, Is it already defined function can asynchronous only or we can make them according our need.

Share Improve this question edited Aug 25, 2015 at 7:02 seenukarthi 8,64410 gold badges50 silver badges73 bronze badges asked Aug 25, 2015 at 6:48 AnkitAnkit 2213 gold badges6 silver badges13 bronze badges 1
  • Not sure what exactly you are asking, but i think what you are looking is control flow. For that, take a look at npmjs./package/async or even better with promises and generators. gist.github./swarajgiri/16202e32aa4d80d45c62 – Swaraj Giri Commented Aug 25, 2015 at 6:51
Add a ment  | 

3 Answers 3

Reset to default 10

There are multiple ways to achieve this in JavaScript (not node-specific, but there are modules that make your life easier):


callbacks

They are somewhat continuations and it is a shame developers were bothered with handling them manually (pilers used to do that themselves). But they work:

function callee(callback) {
  setTimeout(function() {
    callback(null, 'finished!');
  }, 2000);
}

function caller() {
  document.write('started!');
  callee(function(err, result) {
    document.write(result);
  });
}

caller();

It is mon in the node environment to indicate errors with the first parameter of the callback (like callback(new Error("something wrong!"))).


promises

As callbacks get ugly when nested (imagine 10-20 of them, you'd be screwed debugging this), the idea of promises came up. You might know them as Futures from java. They are built-in to ES6, and you can use them beforehand in the node environment with npm i promise -- many client-side frameworks (e.g. jQuery, AngularJS) have their own implementations. Originally there was Q.

var Promise = require('promise');

function callee() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('finished!');
    }, 1000);
  });
}

function caller() {
  document.write('started!');
  callee().then(function(result) {
    document.write(result);
  });
}

caller();


generators

ES6 has generators. You might know them from python.

They provide asynchronity as well, as they yield new values once they are puted.

I remend reading Learn ES2015 for more information on that.

My personal opinion is to never ever use generators as they interfere heavily with promises and make debugging really hard.


async/await

ES7 will make life a whole lot easier with async/await. You can basically say that a function will be performed asynchronously and that you want to await a result (once you are in a async function). ES7 async functions is a good start to read on that. It's like

async function callee() {
  return (() => {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve('finished!'), 1000);
    })
  })();
}

async function caller() {
  document.write('started!');
  document.write(await callee());
}

// the global async wrapper
(async function() {
  caller();
})();

I have tried to provide a better version of @Dominik Schreiber's answer

async function callee() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('finished!'), 1000);
  })
}

async function caller() {
  console.log('started!');
  console.log(await callee());
}

caller();

You can add a callback to the event que with

 process.nextTick(callback);

Don't do that, it is almost never what you want. JavaScript is single threaded so adding a callback still blocks the call of f2. If you have a function that takes a long time to run run it in a child_process or even better, create a separate micro service for it.

发布评论

评论列表(0)

  1. 暂无评论