javascript javascript承诺不传递所有参数(使用Q)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17970420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:16:09  来源:igfitidea点击:

javascript promise not passing all arguments (using Q)

javascriptnode.jspromisedeferredq

提问by Nick

I am having trouble passing all arguments. My promise callback only receives one instead of three:

我无法传递所有参数。我的承诺回调只收到一个而不是三个:

var asyncFunction= function(resolve) {
    setTimeout(function() {
        resolve("Some string that is passed", "and another", "third");
    }, 1000);
};

var promiseFunction = function () {
    var deferred = Q.defer();

    asyncFunction(deferred.resolve);

    return deferred.promise;
};

promiseFunction().then(function() {
    // Only one argument is passed here instead of 3
    // { '0': 'Some string that is passed' }
    console.log(arguments); 
});

Any idea what I am doing wrong?

知道我做错了什么吗?

采纳答案by Bergi

Q promises can be resolved with only one argument - a promise stands for one single value, not for a collection of them. Put them in an array explicitly if you need multiple values. For the multiple-parameter-callbacks, you can use .spread().

Q promises 可以resolve只带一个参数——promise 代表一个单一的值,而不是它们的集合。如果您需要多个值,请将它们显式放入一个数组中。对于多参数回调,您可以使用.spread().

回答by Mariusz Nowak

Synchronous functions return only one value, same way asynchronous should resolve with one.

同步函数只返回一个值,同样的方式异步应该用一个来解析。

It's a bad practice to create async functions that resolve with many values. If you want to pass many values, return them in array or dict object, same as you would do if given function would be synchronous.

创建使用多个值解析的异步函数是一种不好的做法。如果要传递多个值,请在数组或 dict 对象中返回它们,就像给定函数是同步的一样。

回答by user3661094

If you want to pass along multiple values, you must wrap them in another single value that you pass, such as an array or an object.

如果要传递多个值,则必须将它们包装在传递的另一个值中,例如数组或对象。