在我的情况下,如何将参数传递到函数中

How to pass parameter into a function in my case

本文关键字:参数传递 函数 我的 情况下      更新时间:2023-09-26

我正在尝试为我的应用程序建立承诺。我有类似的东西

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');

我在控制台中获得了所需的数据.log

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

如果从

处理程序返回承诺,则从匹配.then()返回的承诺将适应该承诺,从而允许您执行以下操作:

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

你试过吗

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

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

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

当你不使用getProductName(companyID)时,它会失败,因为公司ID是未定义的,所以你需要在你的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');