javascript - 访问有关导致 indexedDB 中请求出错的数据对象的信息

标签 javascript function closures indexeddb

如果对indexedDB的请求失败,错误处理程序中是否有办法记录有关未添加到数据库的数据对象的信息?我在事件对象中查找,但没有找到任何内容。

在下面的代码中,我尝试将数据元素 d 从文本文件 t 写入对象存储 s 但不这样做如果一个或多个数据元素出错,不希望事务回滚。如果出现错误,我想将失败的数据记录在req_err数组中,并继续写入“好的”数据。 “坏”数据将显示给用户纠正或丢弃。

下面的代码按现在的方式工作,但似乎应该有一种方法可以做到这一点,而无需创建数组的请求元素并向请求对象添加属性,然后使用 this< 访问它们 在错误事件处理程序中。

当变量req是标量时,解析失败的数据元素会被毫无问题地记录下来,因为循环计数器i的值被用作数组 n 中引用数据的索引在使用时为“当前”。但是导致添加请求失败的数据不能使用循环计数器作为引用,因为当请求完成时,循环已完成并且 i 等于 l,循环的顶部值。对于对象q也是如此。它始终是该点文件中的最后一个数据元素。我需要类似事件处理程序的闭包之类的东西。

我的问题是,iq 是否可以在不使用 req 的情况下提供给 req.onerror 事件处理程序> 一个数组并将它们添加为它的属性?或者,是否有更好的方法来访问它们?

谢谢。

for ( i = 1; i < l; i++ )
  { 
    d = t.substring( x, x + map[i] ); 
    try
      {
        q = JSON.parse( d  ); 
      }
    catch
      {
        q = { "id" : n[i].key, "data" : "empty data object to be inserted here later" }; 
        req_err[ err_cnt ] = { 'q' : n[i].q, 'key' : n[i].key, 'data' : d, 'error' : "Failed to parse the string to an object." };
        err_cnt = err_cnt + 1;
      }
    finally
      {
        x = x + map[i]; 
      }  

    req[i] = s.add( q ); 
    req[i].i = i;
    req[i].q = q;


    req[i].onerror = function( event ) 
      {
        event.preventDefault(); 
        event.stopPropagation();
        req_err[ err_cnt ] = { 'q' : n[this.i].q, 'key' : n[this.i].key, 'data' : this.q, 'error' : event.target.error };
        err_cnt = err_cnt + 1;
      }; // close req.onerror

    req[i].onsuccess = function( event )
      {
        $("#msg").text( 'Processed data element : ' + this.i + ' of ' + l ); 
      };

  }; // next i

最佳答案

it seems that there should be a way to do so without making the requests elements of an array and adding properties to the request objects, and then accessing them using this in the error event handler.

可以避免使用数组,但API不提供参数;您确实需要自己隐藏它们 - 我将其放在 IDBRequest 对象上 - 并使用闭包或 this。我的做法如下:

const records = [...];
records.forEach(record => {
  const request = store.put(record);
  request.put_value = record;
  request.onerror = e => {
    console.log(`failed to put: ${request.put_value}: ${e.message}`);
  };
});

关于javascript - 访问有关导致 indexedDB 中请求出错的数据对象的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472254/

相关文章:

javascript - 使用 JavaScript 抓取/窃听 AJAX 数据?

c - 需要在c中进行base64编码/解码

c++ - 枚举和函数

Javascript 闭包与 Object.createProperty

c# - 有人可以用简单的术语解释 C# 中的 "access to modified closure"吗?

javascript - 如何将 AMAZON_COGNITO_USER_POOLS 与 apollo-client 一起使用

javascript - Monaco Editor 的高度

javascript - 指令中的模板未出现

javascript - 如何使用纯 JavaScript 中的一个递归函数动态创建一个依赖选择列表?

swift - void 函数中意外的非 void 返回值