在 JavaScript 中,有一個(gè)名為“Promise.all”的方法,它允許您并行運(yùn)行一系列 Promise。然而,有時(shí)您可能想連續(xù)履行您的承諾。如果您想確保每個(gè) Promise 依次執(zhí)行,或者需要在執(zhí)行下一個(gè) Promise 時(shí)使用一個(gè) Promise 的結(jié)果,這會(huì)很有用。
有一些您可以通過不同的方式在 JavaScript 中連續(xù)運(yùn)行一系列 Promise。在本文中,我們將介紹其中的一些。
Promise.prototype.then()
串聯(lián)運(yùn)行 Promise 數(shù)組的一種方法是鏈接使用 then() 方法將它們組合在一起。該方法接受一個(gè)函數(shù)作為輸入,該函數(shù)將在 Promise 完成后執(zhí)行。
示例
<html>
<head>
<title>Examples</title>
</head>
<body>
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
<script>
Promise.resolve(1) .then(result => {
document.getElementById("result1").innerHTML = result
return Promise.resolve(2);
}) .then(result => {
document.getElementById("result2").innerHTML = result
return Promise.resolve(3);
}) .then(result => {
document.getElementById("result3").innerHTML = result
});
</script>
</body>
</html>
登錄后復(fù)制
如您所見,我們使用 then() 方法將三個(gè) Promise 鏈接在一起。第一個(gè) Promise 解析為值 1,并顯示該值。第二個(gè) Promise 解析為值 2,該值也被顯示。最后,第三個(gè) Promise 解析為值 3,并顯示該值。
因?yàn)椤皌hen”方法返回一個(gè) Promise,所以我們可以通過這種方式將 Promise 鏈接在一起以創(chuàng)建一個(gè)系列。
for-await-of
串聯(lián)運(yùn)行 Promise 數(shù)組的另一種方法是使用“for-await-of”循環(huán)。此循環(huán)允許您在 for 循環(huán)內(nèi)使用await 關(guān)鍵字。 wait 關(guān)鍵字暫停代碼的執(zhí)行,直到承諾得到履行。
示例
這是一個(gè)示例 –
<html>
<head>
<title>Example- for-await-of</title>
</head>
<body>
<script>
async function runPromisesInSeries() {
for await (const promise of [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
]) {
const result = await promise;
document.write(result);
document.write("<br>")
}
}
runPromisesInSeries();
</script>
</body>
</html>
登錄后復(fù)制
在此示例中,我們有一個(gè)包含“for-await-of”循環(huán)的異步函數(shù)。該循環(huán)迭代一系列 Promise。對(duì)于數(shù)組中的每個(gè)承諾,我們等待承諾得到履行。一旦履行了 Promise,就會(huì)顯示該值。
使用庫
如果您需要比本機(jī) Promise API 提供的更多功能,您可以使用 Bluebird 等庫或問:這些庫提供了使用 Promise 的附加方法。
例如,Bluebird 提供了一種“映射”方法,允許您將值數(shù)組映射到 Promise 數(shù)組,然后等待所有值要兌現(xiàn)的承諾 –
const Promise = require('bluebird');
Promise.map([1, 2, 3], x => {
return Promise.resolve(x * 2);
}).then(results => {
console.log(results); // [2, 4, 6]
});
登錄后復(fù)制
結(jié)論
在本文中,我們了解了在 JavaScript 中連續(xù)運(yùn)行一系列 Promise 的幾種不同方法。我們已經(jīng)了解了如何使用“then”方法將 Promise 鏈接在一起,如何使用“for-await-of”循環(huán),以及如何使用 Bluebird 或 Q 等庫。
以上就是如何在 JavaScript 中連續(xù)運(yùn)行給定的 Promise 數(shù)組?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!






