gpt4 book ai didi

javascript - 如何停止 Promise 对象的自动解析?

转载 作者:行者123 更新时间:2023-11-30 11:55:59 26 4
gpt4 key购买 nike

考虑这段代码:

function foo() {
return promiseFoo.then((res) => {
//...
//Construct a `promiseBar` object which is promise-like,
//but also has other uses.
//...
return promiseBar;
});
}

foo().then((res) => {
//Because `promiseBar` is promise-like, it was automatically resolved.
//So now, `res` is, for example, a primitive string instead of the
//original `promiseBar` object
})

有什么方法可以防止自动解析类似 promise 的对象吗?

最佳答案

你会把它包装在一个容器对象中,然后用解构打开它:

function foo() {
return promiseFoo.then((res) => {
//...
//Construct a `promiseBar` object which is promise-like,
//but also has other uses.
//...
return [promiseBar];
});
}

foo().then(([res]) => {
//Because it is an array, promiseBar is not resolved here
});

公平地说,在使用 promises 的几年里,我从来没有真正需要自己这样做,所以我想知道你实际上在做什么 - 请分享。

关于javascript - 如何停止 Promise 对象的自动解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959086/

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