现在我有
getUserInfo = (data) => {
console.log('Getting user info')
return new Promise((resolve, reject) => {
if (data === 1)
return resolve('Hello World')
resolve(getUserInfo(1))
})
}
getUserInfo().then(data => console.log(data))
这将是console.log
Getting user info
Getting user info
Hello World
这正是我想要的,多次致电承诺然后解决。
但是我想在承诺之间添加延迟,所以我希望:
Getting user Info
Wait 1 second
Getting user Info
Hello World
我想使用蓝鸟的Promise.delay。有关如何去的任何提示?
我试过
getUserInfo = (data) => {
console.log('Getting user info')
return new Promise.delay(500,(resolve, reject) => {
if (data === 1)
return resolve('Hello World')
resolve(getUserInfo(1))
})
}
但是作为promise的解析数据会返回Function:
Getting user info
[Function]
提前谢谢!
答案 0 :(得分:2)
延迟是一个承诺,而不是承诺构造函数。所以你可以像任何其他承诺一样使用Promise.delay ..
以下可能是你的 - >
const getUserInfo = (data) => {
console.log('Getting user info')
return new Promise((resolve, reject) => {
if (data === 1) {
return resolve('Hello World')
}
return Promise.delay(500).then(
function () { resolve(getUserInfo(1)); }
);
})
}
getUserInfo().then(data => console.log(data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.min.js"></script>
使用新的async / await,可以使这样的事情变得更容易。
const getUserInfo = async (data) => {
console.log('Getting user info')
if (data === 1) return "hello World";
await Promise.delay(500);
return getUserInfo(1);
}
getUserInfo().then(data => console.log(data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.min.js"></script>