简体   繁体   English

使用$ q Promise,将参数传递给下一个函数

[英]Using $q promises, passing arguments to next function

For promises, is there an accepted method to pass more than one parameter to the next function in a promise chain? 对于Promise,是否存在一种接受的方法来将多个参数传递给Promise链中的下一个函数?

Some background: 一些背景:

I have a project in which we are using promises to handle asynchronous calls to a database. 我有一个项目,我们在其中使用Promise处理对数据库的异步调用。 I have a function in a library we are using that's roughly of the form: 我在我们正在使用的库中有一个函数,其形式大致如下:

executeSql(statement, options, successCallback, failCallback)

Since this is in a long string of promises, I need to make it also into a promise so I can .then it. 由于这是一长串的承诺,因此我需要将其也变成一个承诺,这样我就可以了。

I tried the following: 我尝试了以下方法:

$q(function(resolve, reject) {
    executeSql(statement, options, resolve, reject);
}).then(function(tx, results) {
    alert(tx);
    alert(results);
}

The first parameter comes through fine, but the second does not. 第一个参数很好,但是第二个参数没有。 If I do this: 如果我这样做:

executeSql(statement, options, function(tx, results) {
    alert(tx);
    alert(results);
}, null);

everything works as expected. 一切都按预期进行。

It seems like a promise only sends a single parameter to the next .then function. 似乎promise只向下一个.then函数发送一个参数。 Unfortunately, since the first one is the one I don't care about and only one gets sent along, I have no way to access the results. 不幸的是,由于第一个是我不关心的,只有一个被发送,所以我无法访问结果。

I have a workaround for this specific issue, but my general question remains. 对于这个特定问题,我有一种解决方法,但是我的一般问题仍然存在。

For reference, the workaround is: 供参考,解决方法是:

$q(function(resolve, reject) {
    executeSql(statement, options, function(tx, results) {
        resolve(results);
    }, reject);
 });

But that only works because I only care about passing on the results in this particular case. 但这只能奏效,因为我只关心在这种特殊情况下传递结果。

According to the AngularJS $q API , you can only pass a single parameter to the resolve function. 根据AngularJS $ q API ,您只能将单个参数传递给resolve函数。 So to pass multiple variables you'd have to wrap them in an object. 因此,要传递多个变量,您必须将它们包装在一个对象中。 Ie you could call: 即您可以致电:

resolve({'tx':tx, 'results':results})

and your then function would look something like: 然后您的then函数将类似于:

.then(function(wrapperObj) {
  alert(wrapperObj.tx);
  alert(wrapperObj.results);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM