Javascript Promises 返回奇怪的对象

标签 javascript promise google-chrome-app

(function() {
"use strict";

var storage = chrome.storage.sync;
var localStorage = null;

function getOutsideScope(property) {
    if (localStorage.hasOwnProperty(property)) {
        return localStorage[property];
    }
}

function fulfill(data) {
    return data;
}

function rejected(err) {
    log(err);
}

window.app.storage = {
    get: function(storageKey, storageProp) {
        var promise = new Promise(function(fullfill, reject) {
            chrome.storage.sync.get(storageKey, function(data) {
                if (data.hasOwnProperty(storageKey)) {
                    fullfill(data[storageKey]);
                } else {
                    reject(new Error(storageKey + " does not exist in the storage values."));
                }
            });
        });
        return promise.then(fulfill, rejected);
    },
    set: function(storageKey, storageItem) {

    },
    onChanged: function(fn) {

    }
};

})();

所以上面是我的用于 chrome 存储的 IIFE 包装器,而返回是令人痛苦的。所以我决定尝试一下 Promise,这是我第一次,所以不要对我太粗暴。基本上这就是我想做的

 var property = app.storage.get("properties");
 //property should equal "value"
 //except it returns undefined 

所以添加 promise 它确实会得到值,除了返回这个

Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "value"}

我在 Promises 方面做错了什么吗?我尝试阅读 HTML5Rocks、MDN 和视频教程,但它并没有真正提及如何返回值。这工作

get:function(storageKey,storageProp) {
    chrome.storage.sync.get(storageKey,function(data) {
        //for simplicity and no error checking -_-
        return data[storageKey];
    });
}

最佳答案

该函数返回的正是它应该返回的内容:一个 promise 。要在 promise 完成后获取值,您可以通过 .then 添加回调:

app.storage.get("properties").then(function(property) {
    // property will be "value"
});

来自MDN :

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

[...]

A pending promise can become either fulfilled with a value, or rejected with a reason (error). When either of these happens, the associated handlers queued up by a promise's then method are called.

关于Javascript Promises 返回奇怪的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323321/

相关文章:

javascript - 从毫秒获取日期

javascript - 如何动态地将对象添加到数组(循环中的闭包)

google-chrome - 如何让通知显示在 Chrome 和 Chrome 操作系统上,例如 Pushbullet 和 Google Now?

javascript - 在 Chrome 应用程序中保存没有保存对话框的文件

javascript - 第一次点击链接 - 滚动动画不起作用

JavaScript - 获取满足第一个条件的值

javascript - Electron Java脚本将数据从渲染传递到主要对象,反之亦然

javascript - 无需过多嵌套即可调用多个 API

javascript - promise 值没有返回,但如果我执行 console.log() ,它会打印该值

google-chrome - 在没有 Chrome 网上应用店付款的情况下接受 Chrome 付款