gpt4 book ai didi

javascript - 一系列 promise 如何在不被消耗/履行的情况下返回?

转载 作者:行者123 更新时间:2023-12-01 02:18:42 26 4
gpt4 key购买 nike

我对下面的代码如何工作感到相当困惑。我希望在 Promise.resolve() 返回一个已解决的 promise 之后 - 而不是一个待处理的 promise - .then() 会立即使用它/履行它,这意味着;在每个reduce回调调用中,都会问两个问题(promise链) - 但实际上它们都是链式的,并且只有在从函数chainPromises返回时,它们才会互相消耗并一起运行。

这是因为我们正在等待“调用堆栈”清空,并且每个 .then() 正在等待前一个 .then() 回调结束,因此它返回一个 promise 等?减少如何发挥作用?

有人可以帮助我更好地理解代码及其背后的概念吗?

var fs = require("fs");
var readline = require("readline");

var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let questionsData = [];

promisifyQuestion('How many languages do you know? \n')
.then((numOfLanguauges) => {
return chainPromises(numOfLanguauges)
})
.then((data) => {
fs.writeFile("./langs.json", JSON.stringify(questionsData), () => {});    
return promisifyQuestion('Display lang?');    
})
.then(x => {    
console.log(JSON.stringify(questionsData.find(el => el.name == x)));    
rl.close();
});


function promisifyQuestion(msg) {    
return new Promise((resolve, reject) => {
rl.question(msg, resolve);    
});
}

function chainPromises(length) {
for (var i = 0; i < length; questionsData[i++] = {});

let singleValue = questionsData.reduce(outerReduce, Promise.resolve());
//Promise chain does fire only on chainPromises end
return singleValue;
}

function outerReduce(prevRes, currentElement, currentIndex) {
return prevRes
.then(() => promisifyQuestion('language name:'))
    .then(x => {    
questionsData[currentIndex].name = x;
        
return promisifyQuestion('years of speaking it:');        
})
.then(x => {
return questionsData[currentIndex].years = x
});
}

最佳答案

Promise 会等待,直到 JavaScript 调用堆栈为空。下面的代码片段打印 1 2 3,表明 .then 回调不会立即运行。从技术上讲,它们被安排在微任务队列中,与事件循环分开。

console.log('1');
Promise.resolve().then(()=>console.log('3'));
console.log('2');

您的示例更长且更复杂,但可以归结为这一点。

一些阅读 Material :

关于javascript - 一系列 promise 如何在不被消耗/履行的情况下返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49364817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com