无法访问Promise返回的对象的属性

时间:2019-05-31 00:19:43

标签: javascript ecmascript-6 promise

我有以下对象:

const api = {
    post: () => {
        return new Promise((resolve, reject) => {
            resolve({
                response: {
                    data: {
                        token: "abcdefghijkl",
                    },
                 },
              });
        })
      }
   };

当我做api.post().then((res) => console.log(res.data))时 即使undefined打印整个对象,我也得到console.log(res)

2 个答案:

答案 0 :(得分:0)

尝试一下:

const api = {
    post: () => {
        return new Promise((resolve, reject) => {
            resolve({
                response: {
                    data: {
                        token: "abcdefghijkl",
                    },
                 },
              });
        })
      }
   };

api.post().then((res) => console.log(res.response.data))

答案 1 :(得分:-1)

应该为res.response.data

api.post().then((res) => console.log(res.response.data)

或者,如果您想通过res.data访问它,请将从诺言返回的对象更新为

resolve({
  data: {
    token: "abcdefghijkl",
  }
});