簡體   English   中英

在 promise.then 回調后執行一個動作

[英]Perform an action after a promise.then callback

我正在嘗試將一些初始化/清理代碼封裝在一個 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'));

這在終端中給了我以下 output:

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

到目前為止一切都很好。 但是,當我們使回調異步時,它就不再起作用了。

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

給我這個 output:

initialization
cleanup
- Promise {<pending>}
execute then

我本來希望它看起來像這樣:

initialization
- Promise {<pending>}
execute then
cleanup

我怎樣才能解決這個問題? 這有可能嗎?

您可以接受定義異步操作的回調。 然后它可以插入到 promise 鏈的中間:

 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM