我这里的用例:
有更好的设计模式吗?
let twoStagePromise = (state: boolean): Promise<{ ready: boolean, wait: Promise; }> => {
return new Promise((resolve, reject) => {
try {
if (state) {
resolve({
ready: true,
wait: new Promise((resolve, reject) => {
resolve([1, 2, 3]);
})
});
} else {
resolve({
ready: false,
wait: new Promise((resolve, reject) => {
setTimeout(() => { resolve([1, 2, 3]); }, 1000);
})
});
}
} catch (e) {
reject(e);
}
});
};
twoStagePromise(false).then((data) => {
if (!data.ready) {
console.log('loading...');
}
return data.wait;
}).then((result) => {
console.log("recieved result", result);
}).catch((error) => {
console.log("try-catch failed or inner promise failed")
});
阅读了一些评论后,我大大简化了代码:
let twoStagePromise = (state: boolean): Promise> => { return new Promise((resolve, reject) => { try { if (state) { resolve([1, 2, 3]); } else { resolve(new Promise((resolve) => setTimeout(() => { resolve([1,2,3]) }, 1000))) } } catch (e) { reject(e); } }); }; twoStagePromise(false).then((dataOrPromise) => { if (dataOrPromise instanceof Promise) { console.log('loading...'); } return dataOrPromise // continue the promise chain by returning the promise or data }).then((result) => { console.log("recieved result", result); }).catch((error) => { console.log("try-catch failed or inner promise failed", error) });
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以创建一个显式返回值或其承诺的函数。无论如何你都可以轻松地
await了。要检查结果是否同步,请使用result instanceof Promise