在promise.then回调之后执行操作



我正试图将一些初始化/清理代码封装在一个Promise中。我想要的是执行一些代码,执行然后再执行一些代码。这就是我想到的:

function initialize() {
let callback;
console.log('intialization');
const promise = new Promise(resolve => callback = resolve);
new Promise(async () => {
await callback();
await promise;
console.log('cleanup');
});
return promise;
}
initialize().then(() => console.log('execute then'));

它在终端中给我以下输出:

initialization
execute then
cleanup
- Promise {<fulfilled>: undefined}

到目前为止一切都很好。然而,当我们使回调异步时,它就不再工作了。

initialize().then(
async () => {
await new Promise(resolve => {
setTimeout(
() => {
console.log('execute then');
resolve();
},
10000
)
})
}
);

给我这个输出:

initialization
cleanup
- Promise {<pending>}
execute then

我本以为它会是这样的:

initialization
- Promise {<pending>}
execute then
cleanup

我该怎么解决这个问题?这可能吗?

您可以接受定义异步操作的回调。然后它可以插入到承诺链的中间:

const delayMessage = (message, ms) =>
new Promise(resolve => setTimeout(() => {
console.log(message);
resolve();
}, ms));
async function somethingAsync() {
console.log('intialization');
}
function initialize(callback) {
return somethingAsync()
.then(callback)
.then(() => {
console.log('cleanup');
});
}
const middleOfProcess = () => delayMessage('execute then', 2000);
initialize(middleOfProcess);

即使中间有多个异步步骤要做,它也能工作,因为你可以简单地将它们链接在一起:

const delayMessage = (message, ms) =>
new Promise(resolve => setTimeout(() => {
console.log(message);
resolve();
}, ms));
async function somethingAsync() {
console.log('intialization');
}
function initialize(callback) {
return somethingAsync()
.then(callback)
.then(() => {
console.log('cleanup');
});
}
const middleOfProcess = () => delayMessage('execute then1', 2000)
.then(() => delayMessage('execute then2', 2000))
.then(() => delayMessage('execute then3', 2000));
initialize(middleOfProcess);

使用async/await语法也可以做到这一点:

const delayMessage = (message, ms) =>
new Promise(resolve => setTimeout(() => {
console.log(message);
resolve();
}, ms));
async function somethingAsync() {
console.log('intialization');
}
async function initialize(callback) {
await somethingAsync();
await callback();
console.log('cleanup');
}
const middleOfProcess = async () => {
await delayMessage('execute then1', 2000);
await delayMessage('execute then2', 2000);
await delayMessage('execute then3', 2000);
};
initialize(middleOfProcess);

相关内容

  • 没有找到相关文章

最新更新