【问题标题】:Pouchdb db `allDocs` iteration not returning value in Reactjs to another filePouchdb db`allDocs`迭代没有将Reactjs中的值返回到另一个文件
【发布时间】:2020-09-14 05:42:10
【问题描述】:

我有 PouchDb 作为本地存储和一个 Reactjs 文件,我从中调用 DB 函数。

代码是这样的

观点>>>>>>>>>>

import React from 'react';
import person  from '../localstore/test'
var person1 = new person();
var settext=[];
settext.push("The amazing devops");  

function Bigtag() {
  var gottext=person1.gettingthetag();
  settext.push(gottext);
  console.log("The object pushed is : "+gottext); // or i have used settext[1].
  return (
  <h1>{settext}</h1>
  );
}

export default Bigtag;

DB控制器是这样的。

import PouchDB from 'pouchdb';
const db = new PouchDB('bigTag');
var biggertext = ["Default"];

function getbigtag() {
  this.gettingthetag = function() {
    db.allDocs({
      include_docs: true,
      descending: true,
      limit: 1
    }, (err, doc) => {
      doc.rows.forEach(e => {
        var exploded = JSON.stringify(e.doc)
        var parsec = JSON.parse(exploded)
        biggertext.push(parsec.bigtext);
        console.log("The upper function has pushed the data in array : " + parsec.bigtext)
        console.log("The upper function has pushed the data in array at 1 : " + biggertext[1]) // value is pushed and can be fetched here 
        return biggertext; //or return biggertext[1]/// I CANNOT ACCESS THIS VALUE IN THE BIGTAG FILE..                 
      });
    }).catch((err) => {
      //console.error(err);
    });
  }
}

export default getbigtag;

因此,返回函数不会将值返回到我从中调用函数的 Bigtag 文件中。我得到推送的对象是:未定义。我知道它是一个异步函数,但它应该正确填充数组。我也无法在外面调用数组。

【问题讨论】:

    标签: javascript reactjs pouchdb


    【解决方案1】:

    代码有点到处都有多个问题 - 例如,将 allDocs 回调样式与基于 Promise 的 catch 混合:

    db.allDocs({ include_docs: true, descending: true, limit:1 }, (err, doc) => {
      // snip
    }).catch((err) => {
      // snip
    });
    

    对于回调样式,参数 err 是您在 Promises catch 中所期望的。

    如果可能,不要使用难以管理的回调样式。请务必使用异步函数或 Promises。

    另一个问题是biggertextforEach 中的返回语句:

    doc.rows.forEach(e => {
      var exploded =  JSON.stringify(e.doc)
      var parsec = JSON.parse(exploded)
      biggertext.push (parsec.bigtext);
      // exactly where is this return value landing?
      return biggertext; 
    });
    

    正如所评论的,究竟是什么接收了该返回值? (提示:什么都没有)。

    下面是一段代码 sn-p,以某种方式展示了 Async、Promise 和 Callback 样式。例如 Promise 样式函数:

      this.gettingthetag_promise = () => {
        return db.allDocs({
          include_docs: true,
          descending: true,
          limit: 1
        }).then(response => {
          response.rows.forEach(row => {
            this.biggertext.push(row.doc.text);
          });
          return this.biggertext;
        });
      };
    

    示例 pouchdb 有一个带有文本 Kittens 的文档 - 因为说真的,谁不喜欢小猫?

    function getbigtag() {
      // zero reason to have this as a global.
      this.biggertext = ["Default"];
      // Use Async. Just do it.
      this.gettingthetag_async = async() => {
        try {
          const response = await db.allDocs({
            include_docs: true,
            descending: true,
            limit: 1
          });
    
          response.rows.forEach(row => {
            this.biggertext.push(row.doc.text);
          });
    
        } catch (err) {
          this.biggertext.push(err.toString());
        };
        return this.biggertext;
      };
    
      // Promises are nostalgic.
      this.gettingthetag_promise = () => {
        return db.allDocs({
          include_docs: true,
          descending: true,
          limit: 1
        }).then(response => {
          response.rows.forEach(row => {
            this.biggertext.push(row.doc.text);
          });
          return this.biggertext;
        });
      };
    
      // The road to hell is paved with callback functions.
      this.gettingthetag_callback = (cbFn) => {
        db.allDocs({
          include_docs: true,
          descending: true,
          limit: 1
        }, (err, response) => {
          if (err) {
            this.biggertext.push(err.toString());
          } else {
            response.rows.forEach(row => {
              this.biggertext.push(row.doc.text);
            });
          }
          // make the callback with the value.
          cbFn(this.biggertext);
        });
      }
      return this;
    }
    
    function get(which) {
      // clear result columns
      getEl('async_results').innerText = '';
      getEl('promise_results').innerText = '';
      getEl('callback_results').innerText = '';
    
      const tag = getbigtag();
    
      switch (which) {
        case 'async_results':
          (async() => {
            try {
              getEl(which).innerText = await tag.gettingthetag_async();
            } catch (err) {
              getEl(which).innerText = err.toString();
            }
          })();
          break;
        case 'promise_results':
          tag.gettingthetag_promise().then(that => {
            getEl(which).innerText = that;
          }).catch(err => {
            getEl(which).innerText = err.toString();
          });
          break;
        case 'callback_results':
          const my_callback = (that) => {
            getEl(which).innerText = that;
          }
          tag.gettingthetag_callback(my_callback);
          break;
      }
    }
    
    //
    //  boilerplate code
    //
    let db;
    
    // init example db instance
    async function initDb() {
    
      db = new PouchDB('test', {
        adapter: 'memory'
      });
    
      await db.bulkDocs(getDocsToInstall());
    }
    
    // canned test documents
    function getDocsToInstall() {
      return [{
        text: "Kittens"
      }]
    }
    
    
    initDb().then(() => {
      getEl('view').classList.remove('hide')
    });
    
    const getEl = id => document.getElementById(id);
    .hide {
      display: none
    }
    
    .label {
      text-align: right;
      margin-right: 1em;
    }
    
    .hints {
      font-size: smaller;
    }
    <script src="//cdn.jsdelivr.net/npm/pouchdb@7.1.1/dist/pouchdb.min.js"></script>
    <script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script>
    <script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.find.js"></script>
    <table id='view' class='hide'>
      <tr>
        <td>
          <button onclick='get("async_results")'>get via async</button>
        </td>
        <td>
          <button onclick='get("promise_results")'>get via promise</button>
        </td>
        <td>
          <button onclick='get("callback_results")'>get via callback</button>
        </td>
      </tr>
      <tr>
        <td id='async_results'>
        </td>
        <td id='promise_results'>
        </td>
        <td id='callback_results'>
        </td>
      </tr>
    </table>
    <div style='margin-top:2em'></div>
    <div id='results' class='hide'>
    </div>

    祝你好运!

    【讨论】:

    • 很抱歉回复晚了,但我们从早上开始就停电了。这一点我已经有些理解了。会做我所有的 RnD,如果我遇到困难,我会回复。感谢您的帮助。我欠你咖啡/啤酒……随便你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    相关资源
    最近更新 更多