javascript promise not passing all arguments (using Q)

天大地大妈咪最大 提交于 2019-12-17 06:51:57

问题


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?


回答1:


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().




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/17970420/javascript-promise-not-passing-all-arguments-using-q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!