带有 Promise 解析值的 setTimeout 函数作为回调

setTimeout function with Promise resolve value as a callback

我有一段代码让我很困惑,所以我会试着把它贴在这里,并用文字写下我认为它是如何执行的,它可能不正确,所以你可以纠正我。

const wait = function(seconds) {
  return new Promise(function(resolve) {
    setTimeout(resolve, seconds * 1000);
  });
};

wait(1)
  .then(() => {
    console.log(`1 second passed`);
    return wait(1);
  })
  .then(() => {
    console.log(`2 second passed`);
    return wait(1);
  })
  .then(() => {
    console.log(`3 second passed`);
    return wait(1);
  })
  .then(() => {
    console.log(`4 second passed`);
    return wait(1);
  })
  .then(() => console.log(`5 second passed`));

所以我比较迷惑的地方是在setTimeout函数里面设置了'resolve'作为回调,我会一步步写下去,有错的可以指正。

除了一个小问题,你的解释还不错:

Since our 'resolve' is empty we can't use 'then' method's argument RIGHT?

可以,只是它的值会是undefined。不带参数调用 resolve 的结果与使用 undefined 调用它的结果完全相同: promise 的实现值是值 undefined:

const wait = ms => new Promise(resolve => {
    setTimeout(resolve, ms);
});

wait(200)
.then(result => {
    console.log(`result is: ${result}`);
});

wait(200)
.then((...args) => {
    console.log(`args.length is: ${args.length}`);
});

请注意,即使我们调用 resolve 时不带任何参数,执行处理程序始终只使用一个参数调用。

总的来说,你的解释看起来不错。只是第4、5步有点错误。

Step: 4 ....Since our 'resolve' is empty we can't use '.then' method's argument RIGHT...

答案是否定的。 你仍然可以.then,数据将是undefined

var wait = function (seconds) {
  return new Promise(function (resolve) {
    setTimeout(resolve, seconds * 1000);
  });
};

wait(1)
  .then(() => {
    console.log(`1 second passed`);
  }).then((data) => { console.log("Result: " + data) });

同时,如果你 return Promise 甚至任何值,它仍然是解决下一个 .then 的值。

var wait = function (seconds) {
  return new Promise(function (resolve) {
    setTimeout(resolve, seconds * 1000);
  });
};

wait(1)
  .then(() => {
    console.log(`1 second passed`);
    return 999;
  }).then((data) => { console.log(data) });

Step: 5 - We are returning a new promise so we can chain methods.

实际上,new promise的值将是下一个.then链的值。

比如我们说setTimeout里面的resolve的具体值,那是怎么回事?

const wait = (expectedValue, seconds) => {
  return new Promise(function (resolve) {
    setTimeout(() => resolve(expectedValue), seconds * 1000);
  });
};

wait(100, 1)
  .then((data) => {
    console.log(`1 second passed, Value = ${data}`);
    return wait(200, 1);
  }).then((data) => {
    console.log(`1 second passed, Value = ${data}`);
  })