异步函数后返回值

时间:2016-02-20 13:45:08

标签: javascript asynchronous

我无法理解如何将值从uniqueCheck()返回到isValid。我在setTimeout中添加了模拟异步操作。

function isValid(data) {

    uniqueCheck(data, function(val) {
        return val;
        //true
    });
    // need the value here
}

function uniqueCheck(data, cb) {

    // do something with data async
    setTimeout(function () {

        cb(true)

    }, 1000);

}

console.log(isValid("some data"));

2 个答案:

答案 0 :(得分:0)

你必须通过回调函数返回结果

function isValid(data, callback) {

    uniqueCheck(data, function(val) {
       callback(true);
        return val;

        //true
    });
    // need the value here
}

function uniqueCheck(data, cb) {

    // do something with data async
    setTimeout(function () {

        cb(true)

    }, 1000);

}
//console.log(isValid("some data"));
isValid("some data", function(value){
    console.log(value);
});

答案 1 :(得分:0)

要在代码中使用异步调用,可以使用Promises,或者例如,如果使用jQuery,则可以使用Deferred object.

//async function using $.Deferred
function asyncFunction(){
    var dd = $.Deferred();
    setTimeout(function(data) {
        dd.resolve('loaded');
    }, 500);
    return dd.promise();
}

//somwhere in your code
asyncFunction().then(function(value){
    //do stuff when Deferred object is resolved
    //value = 'loaded'

})
你的代码中的

function isValid(data) {
  uniqueCheck(data).then(function(){
    //value is available here

  });
    // but not here
    //because this code is executed earlier then callback
}

function uniqueCheck(data, cb) {
var dd = $.Deferred();
    // do something with data async
    setTimeout(function () {
        cb(true)
    }, 1000); 
 return dd.promise();
}