lundi 27 novembre 2017

How to avoid wrapping code in a promise callback?

In order not to wrap blocks of code in a promise callback (to save one level of indentation), I sometime do the following:

function myFunction() {
    // Create the promise object and get the "resolve" callback
    let promiseResolve = null;
    const promise = new Promise((resolve, reject) => {
        promiseResolve = resolve;
    });

    // Then later in the code:
    setTimeout(() => {
        // Something slow
        promiseResolve();
    }, 1000);

    // And at the end
    return promise
}

It works but it feels a bit messy. Is there any proper pattern to do this in JavaScript?

Aucun commentaire:

Enregistrer un commentaire