开发者

Javascript: What is wrong with this conditional?

开发者 https://www.devze.com 2023-01-31 21:33 出处:网络
I\'m working on a Chrome extension an I\'ve hit a wall. function isInQueue(id) { chrome.extension.sendRequest({getQueueItems: 1}, function(response) {

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 ha开发者_开发知识库ve 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

0

精彩评论

暂无评论...
验证码 换一张
取 消