약속에 onFulfilled에 여러 가지 주장이있을 수 있습니까?
여기에 있는 사양을 따르고 있으며 onFulfilled를 여러 인수로 호출 할 수 있는지 확실하지 않습니다. 예를 들면 다음과 같습니다.
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled('arg1', 'arg2');
})
내 코드는 다음과 같습니다.
promise.then(function(arg1, arg2){
// ....
});
모두받을 arg1
과를 arg2
?
구체적인 약속 구현이 어떻게 수행되는지는 신경 쓰지 않고 w3c 사양을 따르고 싶습니다.
여기에있는 사양을 따르고 있으며 onFulfilled를 여러 인수로 호출 할 수 있는지 확실하지 않습니다.
아니, 첫 번째 매개 변수 만 약속 생성자의 해상도 값으로 처리됩니다. 객체 또는 배열과 같은 복합 값으로 해결할 수 있습니다.
구체적인 약속 구현이 어떻게 수행되는지는 신경 쓰지 않고 w3c 사양을 따르고 싶습니다.
그것이 내가 틀렸다고 믿는 곳입니다. 이 사양은 최소화되도록 설계되었으며 약속 라이브러리간에 상호 운용 되도록 제작되었습니다 . 아이디어는 예를 들어 DOM 선물이 안정적으로 사용할 수 있고 라이브러리가 소비 할 수있는 부분 집합을 갖는 것입니다. 약속의 구현은 지금 당신이 요구하는 것을 수행합니다 .spread
. 예를 들면 다음과 같습니다.
Promise.try(function(){
return ["Hello","World","!"];
}).spread(function(a,b,c){
console.log(a,b+c); // "Hello World!";
});
블루 버드 와 함께 . 이 기능을 원하면 솔루션을 폴리 필하는 것이 좋습니다.
if (!Promise.prototype.spread) {
Promise.prototype.spread = function (fn) {
return this.then(function (args) {
return Promise.all(args); // wait for all
}).then(function(args){
//this is always undefined in A+ complaint, but just in case
return fn.apply(this, args);
});
};
}
이를 통해 다음을 수행 할 수 있습니다.
Promise.resolve(null).then(function(){
return ["Hello","World","!"];
}).spread(function(a,b,c){
console.log(a,b+c);
});
기본 약속으로 쉽게 바이올린 . 또는 브라우저에서 현재 (2018) 일반적인 스프레드를 사용하십시오.
Promise.resolve(["Hello","World","!"]).then(([a,b,c]) => {
console.log(a,b+c);
});
또는 기다리고 있습니다 :
let [a, b, c] = await Promise.resolve(['hello', 'world', '!']);
E6 디스트 럭처링을 사용할 수 있습니다 :
객체 파괴 :
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled({arg1: value1, arg2: value2});
})
promise.then(({arg1, arg2}) => {
// ....
});
배열 파괴 :
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled([value1, value2]);
})
promise.then(([arg1, arg2]) => {
// ....
});
The fulfillment value of a promise parallels the return value of a function and the rejection reason of a promise parallels the thrown exception of a function. Functions cannot return multiple values so promises must not have more than 1 fulfillment value.
As far as I can tell reading the ES6 Promise specification and the standard promise specification theres no clause preventing an implementation from handling this case - however its not implemented in the following libraries:
I assume the reason for them omiting multi arg resolves is to make changing order more succinct (i.e. as you can only return one value in a function it would make the control flow less intuitive) Example:
new Promise(function(resolve, reject) {
return resolve(5, 4);
})
.then(function(x,y) {
console.log(y);
return x; //we can only return 1 value here so the next then will only have 1 argument
})
.then(function(x,y) {
console.log(y);
});
I am looking for the same solution and found seomething very intersting from this answer: Rejecting promises with multiple arguments (like $http) in AngularJS
the answer of this guy Florian
promise = deferred.promise
promise.success = (fn) ->
promise.then (data) ->
fn(data.payload, data.status, {additional: 42})
return promise
promise.error = (fn) ->
promise.then null, (err) ->
fn(err)
return promise
return promise
And to use it:
service.get().success (arg1, arg2, arg3) ->
# => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
# => err
To quote the article below, ""then" takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only."
I usually look to this page for any basic promise questions, let me know if I am wrong
http://www.html5rocks.com/en/tutorials/es6/promises/
Since functions in Javascript can be called with any number of arguments, and the document doesn't place any restriction on the onFulfilled() method's arguments besides the below clause, I think that you can pass multiple arguments to the onFulfilled() method as long as the promise's value is the first argument.
2.2.2.1 it must be called after promise is fulfilled, with promise’s value as its first argument.
Great question, and great answer by Benjamin, Kris, et al - many thanks!
I'm using this in a project and have created a module based on Benjamin Gruenwald's code. It's available on npmjs:
npm i -S promise-spread
Then in your code, do
require('promise-spread');
If you're using a library such as any-promise
var Promise = require('any-promise');
require('promise-spread')(Promise);
Maybe others find this useful, too!
참고URL : https://stackoverflow.com/questions/22773920/can-promises-have-multiple-arguments-to-onfulfilled
'Programing' 카테고리의 다른 글
파이썬에서 문자열로 유니 코드를 선언하는 이유는 무엇입니까? (0) | 2020.07.14 |
---|---|
ImportError : numpy.core.multiarray를 가져 오지 못했습니다. (0) | 2020.07.14 |
Visual Studio 2008에서 후행 공백을 자동으로 제거하는 방법은 무엇입니까? (0) | 2020.07.14 |
잡히지 않는 오류 : SECURITY_ERR : 쿠키를 설정하려고 할 때 DOM 예외 18 (0) | 2020.07.14 |
안드로이드 장치에서 로그 파일을 얻는 방법은 무엇입니까? (0) | 2020.07.14 |