Oli*_*r.B 2 javascript es6-promise
我想用承诺在JS中创建一个虚假的讨论。
console.log等待X秒,
console.log等待X秒...
这是我的代码:
var addMessage = function (msg) {
return new Promise(function (resolve, reject) {
setTimeout( function() {
console.log(msg)
resolve()
}, 2500)
})
}
var scenario = function() {
addMessage('Hello who are you ?')
.then(addMessage('Hello I am John'))
.then(addMessage('Nice too meet you'))
.then(addMessage('Me too'))
.then(addMessage('Good Bye'))
.then(addMessage('Bye'))
}
scenario()
Run Code Online (Sandbox Code Playgroud)
但是使用此代码,所有console.log()都是在同一时间(在2500毫秒后)制作的,我对诺言并不陌生,但我真的不掌握它们。
谢谢 !
托马斯在评论中很好地总结了这一点:
then()需要一个函数,但是addMessage()返回Promise。承诺不是功能。而且,您的所有Promises都是同时创建的,这就是为什么它们同时启动的原因
您正在同时构造所有新的Promises,因此它们将立即执行,并且计时器也将同时在同一时间结束。为了减轻这种情况,您可以addMessage在调用内部包装一个函数.then。
addMessage('Hello who are you ?')
.then(function () { addMessage('Hello I am John') })
.then(function () { addMessage('Nice too meet you') })
.then(function () { addMessage('Me too') })
.then(function () { addMessage('Good Bye') })
.then(function () { addMessage('Bye') })
Run Code Online (Sandbox Code Playgroud)
另外,您也可以使用Function.prototype.bind()避免每次都必须编写匿名函数。
addMessage('Hello who are you ?')
.then(addMessage.bind(null, 'Hello I am John'))
.then(addMessage.bind(null, 'Nice too meet you'))
.then(addMessage.bind(null, 'Me too'))
.then(addMessage.bind(null, 'Good Bye'))
.then(addMessage.bind(null, 'Bye'))
Run Code Online (Sandbox Code Playgroud)
当然,如果您的环境运行的是JavaScript的最新版本,则还可以使用箭头功能:
addMessage('Hello who are you ?')
.then(() => addMessage('Hello I am John'))
.then(() => addMessage('Nice too meet you'))
.then(() => addMessage('Me too'))
.then(() => addMessage('Good Bye'))
.then(() => addMessage('Bye'))
Run Code Online (Sandbox Code Playgroud)
在不久的将来,您还可以使用await关键字,从而.then完全不需要进行任何调用:
await addMessage('Hello who are you ?')
await addMessage('Hello I am John')
await addMessage('Nice too meet you')
await addMessage('Me too')
await addMessage('Good Bye')
await addMessage('Bye')
Run Code Online (Sandbox Code Playgroud)