可以将 Promise 值发送到 next() 内的函数而不是 next() 内的回调吗?

Can a Promise value be sent to a function inside next() instead of a callback inside next()?

问题: 可以将 Promise 值发送到 next() 内的函数而不是 next() 内的回调吗?

背景: 以下标准 Promise 模式按预期工作。 x 等于 1 发送到控制台。

function promisesPromises() {
  return new Promise(function(resolve, reject) {
    let x = 1;
    if (x === 1) {
      resolve('x equals 1');
    } else {
      reject('x does not equal 1');
    }
  });
}

promisesPromises()
  .then(function(data) {
    console.log(data);
  });

然而,当我在 .then() 中调用函数而不是回调函数时,它会抛出错误。

function promisesPromises() {
  return new Promise(function(resolve, reject) {
    let x = 1;
    if (x === 1) {
      resolve('x equals 1');
    } else {
      reject('x does not equal 1');
    }
  });
}

function linkOne(data) {
  console.log(data);
}

promisesPromises()
  .then(linkOne(data));

ReferenceError: data is not defined

我可以通过将函数放在回调函数中来解决这个问题,但这看起来很笨拙。

promisesPromises()
    .then( function(data) {
        linkOne(data);
    });

是否有另一种模式可以实现相同的目标而无需在回调中放置函数?

then 接受一个函数,通过执行 .then(linkOne(data)); 你正在调用 linkOne(data) 并传入结果,因为数据未定义而引发错误。

另一种方法是使用 asnyc/await:

const data = await promisesPromises();
linkOne(data);