在setTimeout中传递多个参数到promise解析 [英] passing multiple arguments to promise resolution within setTimeout

查看:251
本文介绍了在setTimeout中传递多个参数到promise解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to follow along with the MDN promise.all example but it seems I cannot pass more arguments to the 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,两个] 。使用 setTimeout 执行此操作而无需承诺履行按预期工作

This prints [1, "two"], where I would expect [1, 2, 3, "two"]. Doing this with setTimeout without promise fulfillment works as expected

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

为什么不这项工作有希望吗?如何使用承诺?

Why doesn't this work with the promise? How can it be made to work with the promise?

推荐答案

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

The resolve function only takes a single argument. You can't change that as this is the spec.

传递更多不会产生影响,你的其他值也会被忽略。

Passing more than that doesn't make a difference, and your other values are ignored.

您可以选择将数组传递给 resolve 函数,但是您将在上获得一个数组然后处理程序,而不是你想要的独立值。

You can opt to pass an array to the resolve function, but you'll get an array on the then handler, not independent values like you wanted.

这篇关于在setTimeout中传递多个参数到promise解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆