ES6 承诺:如何使用参数链接函数 [英] ES6 promises: how to chain functions with arguments

查看:17
本文介绍了ES6 承诺:如何使用参数链接函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何链接具有延迟的函数.我尝试了以下方法:

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?

推荐答案

.then() 接受一个函数,该函数可能返回也可能不返回承诺

.then() accepts a function, which may or may not return a promise

然而你直接传递了一个承诺

You are however passing a promise directly

// Yes
Promise.resolve().then(() => { return new Promise(); });

// No
Promise.resolve().then(new Promise());

这篇关于ES6 承诺:如何使用参数链接函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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