Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you trace and visualize JavaScript Promises?

In writing a fairly large JavaScript module with lots of async operation all dealing with promises, it becomes quite difficult to debug and follow the flow/state of promises.

Are there any tools or frameworks for instrumenting tests or module code to give he a flow of all the Promises in my system? I'm using jQuery promises if it matters at all.

like image 771
rooftop Avatar asked Apr 01 '13 15:04

rooftop


People also ask

How are JavaScript promises handled?

A Promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.

How do you iterate through a Promise?

JavaScript Promises in For Loops. To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop. In this guide, you learn how async/await works and how it solves the problem of using promises in for loops.

Where are promises used in JavaScript?

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

How do JavaScript promises work under the hood?

You are passing a callback that defines the specific behavior of your promise. A Promise is a container that gives us an API to manage and transform a value, and its specificity is that it lets us manage and transform values that are actually not already there yet.


1 Answers

Off the top of my head, and stimulated by @MrLeap's idea to send messages to the console, how about a creating Deferreds via an "adapter" of your own design.

eg (embryonic and untested) :

var debugMode = true;

function DeferredAdapter(name) {
    var dfrd = $.Deferred();
    if(debugMode) {
        dfrd.notify = function() {
            console.log(name + ': notify');
            if (arguments[0] && typeof arguments[0] == "string")
                console.log(arguments[0]);
        };
        //similar for resolve
        //similar for reject
    }
    return dfrd;
}

This way (when you've got it working), you can do extra stuff when debugging, with a simple mechanism to turn off the extra stuff in production code, without the need to go through all your code purging console.log() statements.

like image 60
Beetroot-Beetroot Avatar answered Oct 04 '22 06:10

Beetroot-Beetroot