考虑以下代码:
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
})
有什么方法可以防止自动解决承诺类对象?
最佳答案
您可以将其包装在容器对象中,然后通过解构将其打开:
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
});
公平地说,在使用诺言的几年中,我从来没有真正自己做过这个,所以我想知道您实际上在做什么-请分享。