在我的情况下如何将参数传递给函数

时间:2015-01-28 18:47:07

标签: javascript angularjs promise

我正在尝试为我的应用构建承诺。我有类似

的东西
var test = function(id,companyID) {
    return getProduct(id)
        .then(getProductName(companyID))
        .then(function(obj) {
              console.log(obj)
        })
}

test('123', '456');

我只能看到一个包含空上下文的对象。但是,如果我将我的代码更改为no,则不包括getProductName函数中的参数和硬编码,如

var test = function(id,companyID) {
    return getProduct(id)
        .then(getProductName)
        .then(function(obj) {
              console.log(obj)
        })
}

test('123', '456');

我在console.log中获得了我需要的数据

我不确定如何将参数传递到链中。知道怎么做吗?非常感谢!

4 个答案:

答案 0 :(得分:1)

你试过

吗?
var test = function(id,companyID) {
    return getProduct(id)
        .then(function(){
            getProductName(companyID)
            .then(function(obj) {
                console.log(obj);
            });
        })
}

答案 1 :(得分:1)

你有没有试过这样的事情:

    var test = function(id, companyID){
    return getProduct(id)
        .then(function(data){
            getproductName(companyID)
                .then(function(data){
                    console.log(obj);
        });
    });
};

答案 2 :(得分:1)

当您不使用getProductName(companyID)时,它会失败,因为未定义companyID,因此您需要在failHandler中使用:

var test = function(id,companyID) {
    return getProduct(id)
        .then(getProductName)
        .then(function(obj) {//doneHandler
              console.log(obj)
        },function(obj){//failHandler
              console.log(obj);//now this gets logged
        })
}

test('123', '456');

答案 3 :(得分:1)

如果从处理程序返回一个promise,那么从匹配的.then()返回的promise将适应该promise,允许你这样做:

var test = function(id,companyID) {
    return getProduct(id)
        .then(function(){
            return getProductName(companyID)
        })
        .then(function(productName) {
            console.log(productName);
        });

}
相关问题