我想用 JS 创建一个带有 promise 的假讨论。
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()
但是使用这段代码,所有 console.log() 都是同时生成的(2500毫秒后),我对 Promise 很陌生,我真的不掌握它们。
谢谢!
最佳答案
托马斯在他的评论中总结得很好:
then() expects a function, but addMessage() returns a Promise. A Promise ain't a function. And, all your Promises are created at the same time, that's why they fire at the same time
您正在同时构建所有新的 Promise,因此它们将立即执行,并且计时器也将同时结束。为了缓解这种情况,您可以将 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') })
或者,您也可以使用 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'))
当然,如果您的环境正在运行最新版本的 JavaScript,您也可以使用 arrow functions :
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'))
在不久的将来,您还可以使用 await keyword这完全消除了任何 .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')
关于javascript - Promise 链接相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44545436/