异步函数自动返回promise-我想知道是否有某种方法可以在函数内部获取此promise的实例 例如,如果我返回这样的实际承诺:
const getSomePromise = () => {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success');
}, 1000);
})
promise.someProp = 'myProp';
return promise;
}
const promise = getSomePromise();
console.log(promise.someProp);
我想通过纯异步功能实现相同的目的:
const sleep = ts => new Promise(resolve => setTimeout(resolve, ts));
const getSomePromise = async () => {
const p = await sleep(1000);
// some how access the instance of the promise from within the async function
// for example this['someProp'] = 'myProp';
// and return the all promise with this prop
return 'sucess';
}
const promise = getSomePromise();
console.log(promise.someProp);
我可以这样做吗?
谢谢
答案 0 :(得分:1)
在诺言中添加财产几乎肯定是个坏主意(稍后在但是下有更多介绍),而只是说说您将如何继续做到:
我想知道是否有某种方法可以在函数内部获取此promise的实例
不,没有。您可以在函数内创建一个Promise,然后将其返回,但这不是函数返回的Promise(它只会影响函数返回的Promise的解析方式)。
如果要将属性添加到返回的诺言中,则必须使用非{async
函数。您可以将函数的整个代码设为非async
:
const sleep = ts => new Promise(resolve => setTimeout(resolve, ts));
const getSomePromise = () => {
const p = sleep(1000).then(() => 'success');
p.someProp = 'myProp';
return p;
}
const promise = getSomePromise();
console.log(promise.someProp);
...或者您可以使用内部async
函数,以便可以使用await
语义,例如:
const sleep = ts => new Promise(resolve => setTimeout(resolve, ts));
const getSomePromise = () => {
const p = (async () => {
await sleep(1000);
return 'success';
})();
p.someProp = 'myProp';
return p;
}
const promise = getSomePromise();
console.log(promise.someProp);
但是:几乎可以肯定的是,向诺言添加属性。取而代之的是,使promise解析为同时具有分辨率和额外someProp
属性的对象:
const sleep = ts => new Promise(resolve => setTimeout(resolve, ts));
const getSomePromise = async () => {
const p = await sleep(1000);
// some how access the instance of the promise from within the async function
// for example this['someProp'] = 'myProp';
// and return the all promise with this prop
return {
result: 'success',
someProp: 'myProp'
};
}
getSomePromise()
.then(resolution => {
console.log(resolution.someProp);
});