gpt4 book ai didi

javascript - 关于链接 es6 Promises、then() 和值消耗

转载 作者:行者123 更新时间:2023-11-30 08:23:47 25 4
gpt4 key购买 nike

这与 Chaining .then() calls in ES6 promises 紧密耦合...

我用一些构成 promise 链的函数尝试了这个,所以基本上:

var PromiseGeneratingMethod = function(){
return p = new Promise((resolve, reject) =>{
resolve(1)
});
}

var inBetweenMethod = function(){
return PromiseGeneratingMethod()
.then((resolved) => {
if(resolved){
console.log('resolved in between');
//return resolved
/* this changes output to
resolved in between
resolved at last*/
}else{
console.log('something went terribly wrong in betweeen', resolved);
}
});
}

inBetweenMethod().then((resolved) =>{
if(resolved){
console.log('resolved at last')
}else{
console.log('something went terribly wrong', resolved);
}
})

/* ouput:
resolved in between
something went terribly wrong undefined*/

我不明白为什么会这样。没有一个 Promise 只有一个关联的返回值?为什么我每次都可以更改该值?这对我来说似乎不合理。一个 Promise 对象只能有一个返回值,我认为在 Promise 得到解决后,每个 then 处理程序都会收到相同的参数?

这样,有两个方法在同一个 Promise 上调用 then(),后一个(在异步环境中你永远不知道那是什么......)将总是得到一个空结果,除非每个 then 返回所需的结果值(value)

如果我做对了,唯一的好处是你可以构建一个 then().then().then() 链来使其几乎同步(通过在每个 then() 中返回任意值)但你仍然可以用嵌套的 Promises 实现同样的效果,对吧?

谁能帮我理解为什么 es6 Promises 以这种方式工作,以及使用它们时是否有更多注意事项?

最佳答案

doesn't have a promise just ONE associated return value?

是的。

why can I change that value in every then?

因为每个 .then() 调用都会返回一个 promise 。

having two methods which call then() on the same Promise

那不是你在做什么。您的 then 回调安装在不同的 promise 上,这就是它们获得不同值的原因。

可以

function inBetweenMethod() {
var promise = PromiseGeneratingMethod();
promise.then(resolved => { … }); // return value is ignored
return promise;
}

但你真的应该避免这种情况。您已经注意到您可以使用

获得预期的行为
function inBetweenMethod() {
var promise = PromiseGeneratingMethod();
var newPromise = promise.then(value => {

return value;
});
return newPromise;
}

其中 newPromise 使用回调返回的值解析 - 可能与 promise 实现的值相同。

关于javascript - 关于链接 es6 Promises、then() 和值消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49070408/

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