通话说无法读取未定义的属性'then(看起来有效)

时间:2019-11-13 01:32:32

标签: javascript reactjs promise es6-promise chaining

我不知道它是否是React.JS,或者只是我忘记了带有Promise的东西,但我遇到了这个错误

const promise = SAIIndexedDB(response.data)
promise.then(function(result){
    this.setState({
         loadingMedications: false                    
    });  
})
.catch(function(error){
    console.log('error', error);
});

错误:

  

TypeError:无法读取未定义的属性'then'

行号显示此行是promise.then(function(result){

我正在阅读此书,这似乎是正确的... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

我想要/需要保证的原因是loadingMedications设置为false,当从函数调用SAIIndexedDB(..)加载完数据后,将关闭微调器。

这是正在调用的函数

export function SAIIndexedDB(customerData){
    var status = "start in helpers";
    const dbName = "SAIOffline";
    var request = indexedDB.open(dbName, 2);
    request.onerror = function(event) {
    };

    request.onupgradeneeded = function(event) {
        var db = event.target.result;
        var objectStore = db.createObjectStore("medications", { keyPath: "value"});
        objectStore.createIndex("short_description", "short_description", { unique: false });
        //objectStore.createIndex("email", "email", { unique: true });
        objectStore.transaction.oncomplete = function(event) {
            // Store values in the newly created objectStore.
            var customerObjectStore = db.transaction("medications", "readwrite").objectStore("medications");
            customerData.forEach(function(customer) {
              customerObjectStore.add(customer);
            });
            status = "done"
            return status;
        };

    };

}

1 个答案:

答案 0 :(得分:1)

请按照以下方式更新您的代码:

SAIIndexedDB(response.data).then(function(result){
    this.setState({
         loadingMedications: false                    
    });  
})
.catch(function(error){
    console.log('error', error);
});
export function SAIIndexedDB(customerData){
    return new Promise((resolve, reject) => {
    var status = "start in helpers";
    const dbName = "SAIOffline";
    var request = indexedDB.open(dbName, 2);
    request.onerror = function(event) {
           reject(event)
    };

    request.onupgradeneeded = function(event) {
        var db = event.target.result;
        var objectStore = db.createObjectStore("medications", { keyPath: "value"});
        objectStore.createIndex("short_description", "short_description", { unique: false });
        //objectStore.createIndex("email", "email", { unique: true });
        objectStore.transaction.oncomplete = function(event) {
            // Store values in the newly created objectStore.
            var customerObjectStore = db.transaction("medications", "readwrite").objectStore("medications");
            customerData.forEach(function(customer) {
              customerObjectStore.add(customer);
            });
            status = "done"
            resolve(status);
        };

    };
}

}