简体   繁体   中英

Javascript: What is wrong with this conditional?

I'm working on a Chrome extension an I've hit a wall.

function isInQueue(id) {
    chrome.extension.sendRequest({getQueueItems: 1}, function(response) {
        var items = response.items;
        if (items) {
            for (var i = 0; i < items.length; i++) {
                if ((items[i].id == id) == true) return true;
            }
            return false;
        } else { return false; }
    });
}

The request returns 'items' which is an array of objects. I am trying to see if another item outside of the queue already exists inside the queue. For example, there is an item on the outside with an id equal to '198677'. I know I already have an exact copy of that same item in my queue with the exact same id, '198677', however, when I test the two for equality (items[i].id == id) == true , it returns false. I have checked the typeof both and they are both strings. I have tried using === and that hasn't worked. I tried adding zero to each of them to turn them into integers and that made the function return true when it was actually true, however, when I tested for true if (isInQueue(id) == true) the conditional returned false.

This is all very confusing and frustrating for me. They're both strings, why doesn't it work?

Help is very much appreciated.

The problem is chrome.extension.sendRequest is asynchronous - it returns immediately, but the callback function you provide to it will only be called once the request has completed.

The usual way to handle something like this is to pass a callback to your isInQueue method; the callback is called when the asynch operation is completed with the result.

function isInQueue(id, callback) {
    chrome.extension.sendRequest({getQueueItems: 1}, function(response) {
        var result = false;
        var items = response.items;
        if (items) {
            for (var i = 0; i < items.length; i++) {
                if ((items[i].id == id) == true) {
                  result = true;
                  break;
                }
            }
        }
        callback(result);
    });
}

I figured it out:

function isInQueue(id) {
    var result = false;
    var queue = localStorage["queue_rss"];
    if (queue != undefined) {
        var items = JSON.parse(queue).items;
        if (items) {
            for (var i = 0; i < items.length; i++) {
                if ((items[i].id == id) == true) {
                  result = true;
                  break;
                }
            }
        }
    }
    return result;
}

I should have done it that way in the first place. Thanks guys. :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM