简体   繁体   English

Node.js和Q Promises:如何以更简洁的方式传递参数?

[英]Node.js and Q Promises: How can I hand over parameters in a cleaner way?

I have some code like this: 我有一些这样的代码:

function example(data){
    asyncFnOne()
        .all([asyncFnTwo(), data])
        .spread(asyncFnThree)
        .done();
};

It doesn't matter what those functions do. 这些功能做什么无关紧要。 The problem I have is that I don't know how asyncFnThree can access both data from asyncFnTwo and from the function parameters. 我遇到的问题是,我不知道asyncFnThree如何访问asyncFnTwo和函数参数中的数据。 The way I solved the problem is not very readable. 我解决问题的方式不是很容易理解。 Is there a recommended way to do this in a clean way? 有没有推荐的方法可以做到这一点?

A second possible soultion would be 第二个可能的灵魂是

function example(data){
    asyncFnOne()
        .then(asyncFnTwo)
        .then(function(result){
            asyncFnThree(result, data);
        })
        .done();
    };
};

But I think it is even less readable. 但是我认为它的可读性更低。

You can use variables as buffers or create some "middle-man" promises. 您可以将变量用作缓冲区或创建一些“中间人”承诺。 You can find some good examples here: http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html?utm_source=javascriptweekly&utm_medium=email 您可以在此处找到一些很好的示例: http : //pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html?utm_source=javascriptweekly&utm_medium=email

To use Q.all in the desired way you'd have to do the following: 若要以所需的方式使用Q.all ,您必须执行以下操作:

function example(data) {
    return Q.all[
        asyncFnOne().then(asyncFnTwo),
        data
    ]).spread(asyncFnThree);
}

Or use a variable for the first part of the chain, so that you don't have to stuff everything in one expression and could use return Q.all([promiseTwo, data])… . 或在链的第一部分使用一个变量,这样您就不return Q.all([promiseTwo, data])…所有内容填充在一个表达式中,而可以使用return Q.all([promiseTwo, data])…

The alternative way with the closure is totally fine as well, and rather standard. 闭包的替代方法也很好,而且很标准。 You might as well use any library that offers some kind of partial application, and use that instead of the function expression. 您也可以使用任何提供某种部分应用程序的库,并使用它代替函数表达式。

function example(data) {
    return asyncFnOne()
    .then(asyncFnTwo)
    .then(asyncFnThree.bind(null, data)); // argument order to asyncFnThree: data, result
}

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

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