期望结果时,异步功能停止工作

时间:2016-03-09 04:51:05

标签: javascript node.js

我的功能如下:

function myAsyncFunction(num){
   if(num>10){
      return true;
   }else{
      return false;
   }
}
然后我以异步方式调用此函数:

myAsyncFunction(100, function(result){

   console.log('The result is = ' + result); //this never gets called

});

但是console.log语句永远不会被打印出来。它应该打印为true或false。

3 个答案:

答案 0 :(得分:0)

你没有正确地做到这一点。您可以传递回调并使用结果调用回调,如下所示

function myAsyncFunction(num, callback){
   if(num > 10){
      callback(true);
   }else{
      callback(false);
   }
}

myAsyncFunction(100, function(result){
   console.log('The result is = ' + result); //this never gets called
});

答案 1 :(得分:0)

例如:“异步”调用JavaScript函数

 function async(fn, callback) {
    setTimeout(function() {
        fn();
        callback();
      }, 0);
    }

function sync(fn) {
    fn();
 }

function foo(){
  console.log('foo');
 }

console.log('SYNC TEST --------------');
//synchronous
console.log('start sync');
sync(foo);
console.log('end sync');
console.log('');

console.log('ASYNC TEST --------------');
//asynchronous
console.log('start async');
async(foo, function(){ 
    console.log('async callback');
});
console.log('end async');

输出

SYNC TEST --------------
start sync
foo
end sync

ASYNC TEST --------------
start async
end async
foo
async callback

答案 2 :(得分:0)

你从未调用过这个函数。

function myAsyncFunction(num,cb){
   if(num>10){
      cb(true);
   }else{
      cb(false);
   }
}


myAsyncFunction(100, function(result){


   console.log('The result is = ' + result); //this never gets called

});