【问题标题】:Javascript Promise.prototype.then() ordering problem [duplicate]Javascript Promise.prototype.then() 排序问题[重复]
【发布时间】:2019-01-05 17:41:01
【问题描述】:

我是 JS 新手。 我刚去了MDN网站 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then 围绕给出的示例进行操作。 我将示例更改为

var promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

promise1
  .then(value => console.log(value))
  .then(console.log('1'))
  .then(console.log('2'))
  .then(console.log('3'))
  .then(console.log('4'))
  .then(console.log('5'));

我希望结果是成功!然后是 1,一直到 5。 但是,结果是1比5,然后成功! 我觉得有点奇怪。 我已经很好地链接了它,但没有“分支”它。非常感谢

【问题讨论】:

标签: javascript


【解决方案1】:

您将console.log 表达式的结果提供给then,而不是在执行时记录数字的函数:

var promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

promise1
  .then(value => console.log(value))
  .then(() => console.log('1'))
  .then(() => console.log('2'))
  .then(() => console.log('3'))
  .then(() => console.log('4'))
  .then(() => console.log('5'));

【讨论】:

  • 啊啊啊啊!!!是的,没错。我应该将一个函数而不是结果传递给.then()。非常感谢!
  • @Ari.Chau 很高兴为您提供帮助!
【解决方案2】:

那是因为你使用了then(console.log(...)) 这将执行console.log 并将结果作为传递给then 的参数

是这样的:

var promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

var par1 = console.log('1'),
    par2 = console.log('2'),
    par3 = console.log('3'),
    par4 = console.log('4'),
    par5 = console.log('5');

promise1
  .then(value => console.log(value))
  .then(par1)
  .then(par2)
  .then(par3)
  .then(par4)
  .then(par5);

【讨论】:

  • 输出还是一样的。另一个答案是对的。
  • @trincot 我不想尝试创建正确的输出。我试图解释他为什么得到这个输出。
  • 我想大多数人不明白。通常人们会给出解释和解决方案的答案......您已经给出了解释和重现问题的另一种方式。 ://
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
相关资源
最近更新 更多