Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

javascript - ES6 promises: how to chain functions with arguments

How to chain functions with delays. I tried the following:

Promise.resolve()
.then(setKeyframe('keyframe-0'))
.then(delay(3000))
.then(setKeyframe('keyframe-1'))
.then(delay(3000))
.then(setKeyframe('keyframe-2'))
;

function delay(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms);
  });
}

function setKeyframe (name) {
  var element = document.getElementsByClassName('animation-container')[0];
  element.className = 'animation-container ' + name;
}

All functions seem to be called immediately after each other. The delay function does not delay the chain. What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your mistake might be easier to spot with a function without arguments:

The right way:

Promise.resolve().then(setFirstKeyframe)

Above, the function setFirstKeyframe is an argument to .then, for the promise to call later.

The wrong way:

Promise.resolve().then(setFirstKeyframe())

Here, setFirstKeyframe is called immediately (!), and its result (a promise) is passed to then (which gets ignored as then expects a function).

For functions with arguments use an anonymous function:

Promise.resolve().then(function() {
  return setFirstKeyframe('keyframe-0');
})

This is where es6 arrow functions rock:

Promise.resolve().then(() => setFirstKeyframe('keyframe-0'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...