因此,我有两个诺言,我希望在屏幕之间进行3秒的延迟打印。我将如何实现。下面是代码。
const promiseOne = new Promise(function(resolve, reject) {
resolve("Hello")
});
const promiseTwo = new Promise(function(resolve, reject) {
resolve("Good Morning")
});
Promise.all([promiseOne, promiseTwo]).then(function() {
setTimeout(() => {
const response = Promise.all.next();
console.log(response);
}, 3000);
});
答案 0 :(得分:0)
您非常接近,您只需要从Promise.all
的结果中接收值,然后处理该信息,就像这样:
const promiseOne = new Promise(function(resolve) {
resolve("Hello")
});
const promiseTwo = new Promise(function(resolve) {
resolve("Good Morning");
});
Promise.all([promiseOne, promiseTwo])
.then(function(response) {
setTimeout(() => {
console.log(response);
}, 3000);
});
修改 根据OP的澄清,他需要的是以下物品:
第一个承诺解决后,等待3秒钟,然后执行第二个承诺。
const promiseOne = new Promise(function(resolve) {
resolve("Hello")
});
const promiseTwo = new Promise(function(resolve) {
resolve("Good Morning");
});
async function resolveWithDelay(delay = 3000) {
const res1 = await promiseOne;
console.log(res1);
setTimeout(async () => {
const res2 = await promiseTwo;
console.log(res2);
}, delay);
}
resolveWithDelay();
答案 1 :(得分:0)
const promiseOne = new Promise(function(resolve, reject) {
resolve("Hello")
});
const promiseTwo = new Promise(function(resolve, reject) {
resolve("Good Morning")
});
Promise.all([promiseOne, promiseTwo]).then(function(all) {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(all);
}
, 3000);
});
}).then(console.log)
在then
中返回新的Promise,该Promise等待x
毫秒并解决。
然后在下一个then
答案 2 :(得分:0)
如果只想延迟日志,则可以按照@Daniel Rodríguez Meza的说明添加response
参数。
但是,如果您要从承诺response
或promiseOne
中的任何一个延迟promiseTwo
,则应在相应的承诺内使用setTimeout(() => resolve("Hello"), 300);
,如下所示。也不要在setTimeout
内使用Promise.All
。
根据OP's comment,我在resolve
解决后更新了对promiseTwo
3 seconds
promiseOne
的答案。
在这里,我已将resolve
的{{1}}分配给全局变量promiseTwo
,该变量在3秒后在resolvePromiseTwo
内用于promiseOne
resolve
注意:我在promiseTwo
和.then
之后使用promiseOne
只是为了验证promiseTwo
。您可以两者都省略。
output
答案 3 :(得分:0)
我建议您使用延迟功能。首先,您遍历数组中的每个响应,并使用之间的延迟
const promiseOne = new Promise(function(resolve, reject) {
resolve("Hello")
});
const promiseTwo = new Promise(function(resolve, reject) {
resolve("Good Morning")
});
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Promise.all([promiseOne, promiseTwo]).then(async function(resps) {
for(let res of resps){
console.log(res);
await delay(3000)
}
});