4 回答

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
我建議你使用延遲功能。首先你遍歷數(shù)組中的每個(gè)響應(yīng)并使用它們之間的延遲
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)
}
});

TA貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
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)
在 中返回新的 Promise then,該 Promise 等待x毫秒并解決它。
接下來做任何事情then

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個(gè)贊
如果您只想延遲日志,則可以按照@Daniel Rodríguez Mezaresponse
的說明添加參數(shù)。
但是如果你想延遲response
任何一個(gè)承諾promiseOne
,promiseTwo
那么你應(yīng)該setTimeout(() => resolve("Hello"), 300);
在各自的承諾中使用,如下所示。也不要setTimeout
在里面使用Promise.All
。
根據(jù)OP 的評(píng)論,resolve
promiseTwo
3 seconds
我在解決后更新了答案promiseOne
。
在這里,我將resolve
of分配給了 3 秒后在內(nèi)部使用的promiseTwo
全局變量。resolvePromiseTwo
promiseOne
resolve
promiseTwo
注意我已經(jīng)使用.then
afterpromiseOne
和promiseTwo
just to verify output
。你可以省略兩者。
let resolvePromiseTwo = null;
const promiseOne = new Promise(function(resolve, reject) {
resolve("Good Morning")
setTimeout(() => resolvePromiseTwo("Hello"), 3000);
}).then(res => {
console.log('promiseOne resolved');
return res;
});
const promiseTwo = new Promise(function(resolve, reject) {
resolvePromiseTwo = resolve;
}).then(res => {
console.log('promiseTwo resolved');
return res;
});
Promise.all([promiseOne, promiseTwo]).then(function(response) {
console.log('Promise.all');
console.log(response);
});

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
你已經(jīng)非常接近了,你只需要從的結(jié)果中接收值,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);
});
編輯 根據(jù) OP 給出的說明,他需要的是以下內(nèi)容:
第一個(gè)promise resolve后,等待3秒再執(zhí)行第二個(gè)promise。
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();
添加回答
舉報(bào)