在setTimeout中传递多个参数到promise解析

时间:2016-09-27 17:11:56

标签: javascript asynchronous promise es6-promise

我试图跟随MDN promise.all示例,但似乎我无法将更多参数传递给setTimeout callback

var p1 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 200, 1,2,3); 
});
var p2 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 500, "two"); 
});

Promise.all([p1, p2]).then(value => { 
  console.log(value);
}, reason => {
  console.log(reason)
});

这会打印[1, "two"],我希望[1, 2, 3, "two"]。使用setTimeout执行此操作而不履行承诺

setTimeout(cb, 100, 1, 2, 3);
function cb(a, b, c){
  console.log(a, b, c);
}
//=>1 2 3

为什么这不符合承诺?如何与承诺合作?

2 个答案:

答案 0 :(得分:9)

resolve函数只接受一个参数。你不能改变它,因为这是规范。

传递更多不会产生影响,而忽略其他值。

您可以选择将数组传递给then函数,但是您将在log into the running container sudo docker exec -i -t containerID# /bin/bash vi /etc/nginx/conf.d/default.conf ssl_certificate /etc/nginx/ssl/demo.pem; ssl_certificate_key /etc/nginx/ssl/demo.key; ssl_session_cache shared:SSL:1m; ssl_prefer_server_ciphers on; server { listen 80; listen 443 ssl; client_max_body_size 2048M; location / { proxy_set_header Host $host; proxy_pass http://localhost:8081/artifactory/; proxy_read_timeout 90; } access_log /var/log/nginx/access.log upstreamlog; location /basic_status { stub_status on; allow all; } } ## Sub domain config for docker repository server { listen 443 ssl; listen 80 ; server_name my-docker-virtual.art.local art.local; if ($http_x_forwarded_proto = '') { set $http_x_forwarded_proto $scheme; } ## Application specific logs access_log /var/log/nginx/docker-access.log; error_log /var/log/nginx/docker-error.log; rewrite ^/(v1|v2)/(.*) /artifactory/api/docker/my-docker-virtual/$1/$2; client_max_body_size 0; chunked_transfer_encoding on; location /artifactory/ { proxy_read_timeout 900; proxy_pass_header Server; proxy_cookie_path ~*^/.* /; proxy_pass http://artifactory_lb/artifactory/ proxy_set_header X-Artifactory-Override-Base-Url $http_x_forwarded_proto://$host:$server_port/artifactory; proxy_set_header X-Forwarded-Port $server_port; proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } 处理程序上获得一个数组,而不是您想要的独立值。

答案 1 :(得分:5)

UITouchGestureRecognizer只接受并处理一个参数,而一个履行的承诺只有一个值。这是承诺规范,不是你可以改变的。

如果要传递多条信息,那么可以将多个数据包装到数组或对象中,并将该一个对象用作已解析的值,然后更改接收代码以在包装中访问它对象:

resolve()

如果您确实希望最终var p1 = new Promise((resolve, reject) => { // put multiple resolved values into an array setTimeout(resolve, 200, [1,2,3]), 200); }); var p2 = new Promise((resolve, reject) => { setTimeout(resolve, 500, "two"); }); Promise.all([p1, p2]).then(value => { console.log(value); // [[1,2,3], "two"] }, reason => { console.log(reason) }); 处理程序中没有嵌入数组的独立值,那么您可以在处理结果之前展平.then()处理程序中的value数组。这里有许多用于展平数组的技术:Merge/flatten an array of arrays in JavaScript?